# 用 CSS 漸層實作斜線背景 Elantris [TOC] ## 需求 有一天設計師希望前端做一個預約時段的功能,頁面上會有一排按鈕讓使用者選擇想要的時段,而按鈕會有三種狀態: - 可預約的時段:一般狀態 - 已過期的時段:灰色背景、使用者不能點按 - 被預約的時段:斜線背景、使用者不能點按 ## 實作 ### 方案一:圖片背景 請設計師提供斜線背景的圖片,用 CSS 套用上去 ```css .slash { background-image: url('/img/slash.png'); background-size: 16px 100%; background-repeat: repeat-x; } ``` 寫法單純簡單,只是需要載入一張圖片而已。 ### 方案二:漸層背景 1. 在原本的按鈕上加入一個偽元素,定位為佔滿整個方塊 ```css .button { position: relative; overflow: hidden; &::before { display: block; position: absolute; top: 0; right: 0; bottom: 0; left: 0; content: " "; } } ``` 2. 利用漸層製造出黑白相間的色塊 讓背景出現兩個色塊:0 ~ 5px 是透明色(transparent)、5px 以後是線條的顏色(#dee2e6),background-size 將寬度限定在 6px 所以灰色線條的實際寬度為 1px。 ```css &::before { background-image: linear-gradient(90deg, transparent 5px, #dee2e6 5px); background-size: 6px 100%; } ``` 3. 加上重複、旋轉、縮放 ```css &::before { background-repeat: repeat; transform: rotate(30deg) scale(2); } ``` ## 完整程式碼 <div class="slash-box"> <span>ABCDE</span> </div> <style> .slash-box { position: relative; display: inline-block; padding: 1.5rem; border: 1px solid #adb5bd; border-radius: 4px; overflow: hidden; > * { position: relative; } &::before { display: block; position: absolute; top: 0; right: 0; bottom: 0; left: 0; content: " "; background-image: linear-gradient(90deg, transparent 5px, #dee2e6 5px); background-size: 6px 100%; background-repeat: repeat; transform: rotate(30deg) scale(2); } } </style> ```html <div class="slash-box"> <span>ABCDE</span> </div> ``` ```css .slash-box { position: relative; display: inline-block; padding: 1.5rem; border: 1px solid #adb5bd; border-radius: 4px; overflow: hidden; > * { position: relative; } &::before { display: block; position: absolute; top: 0; right: 0; bottom: 0; left: 0; content: " "; background-image: linear-gradient(90deg, transparent 5px, #dee2e6 5px); background-size: 6px 100%; background-repeat: repeat; transform: rotate(30deg) scale(2); } } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up