定義與用法
linear-gradient() 函數用於創建一個線性漸變的 "圖像"。
為了創建一個線性漸變,你需要設置一個起始點和一個方向(指定為一個角度)的漸變效果。你還要定義終止色。終止色就是你想讓Gecko去平滑的過渡,並且你必須指定至少兩種,當然也會可以指定更多的顏色去創建更復雜的漸變效果。
CSS 語法
background-image: linear-gradient(direction, color-stop1, color-stop2, ...);
direction: 用角度值指定漸變方向(或角度)
color-stop1, color-stop2, ...: 用於指定漸變的起止顏色
案例
1. 默認漸變方向是從上至下
background: linear-gradient(yellow, green)
2. 可以用角度值定義漸變方向(可以寫成角度 deg)
background: linear-gradient(to top, yellow, green) /*to top 從下至上 相當於 0deg*/ background: linear-gradient(to right, yellow, green) /*to right 從下至上 相當於 90deg*/ background: linear-gradient(to bottom, yellow, green) /*to bottom 從下至上 相當於 180deg*/ background: linear-gradient(to left, yellow, green) /*to left 從下至上 相當於 270deg*/ background: linear-gradient(to top right, yellow, green) /*to top right 沿對角線的方向*/
3. 可以用px或百分比指定起始顏色的位置, 默認值為0%
background: linear-gradient(to top right, yellow 50%, green)
background: linear-gradient(to top right, yellow, green 50%)
background: linear-gradient(to top right, yellow 50%, green 0); /* 注意: 起始顏色的位置是從它自身所占的位置開始計算的, 第一個占了50%, 那第二個的 0 就是從50%開始 */
4. 多次使用 linear-gradient() 時
background: linear-gradient(45deg, rgba(0, 0, 0, 0) 50%, #162e48 0), linear-gradient(135deg, red 40%, blue, transparent 0), linear-gradient(45deg, black, transparent); /* 后面一條會填充前面一條的透明色 */
5. 看到一個按鈕效果, 收藏
<div class="div4"> <div class="div4-1 active">OFF</div> <div class="div4-2">ON</div> </div>
.div4 { width: 144px; height: 30px; line-height: 30px; background: #162e48; color: #fff; text-align: center; margin-bottom: 30px; } .div4-1, .div4-2 { width: 86px; float: left; } .div4-1.active { margin-right: -28px; background: linear-gradient(-135deg, transparent 20px, #f00 0); } .div4-2.active { margin-left: -28px; background: linear-gradient(45deg, transparent 20px, #f00 0); }