CSS 漸變讓我們不必再為了做一層漸層背景而切圖。以下是各瀏覽器的語法對照。
-moz-linear-gradient(起始點, 起始顏色, [中間顏色 百分比], 結束顏色);
起始點可用 left、top、center、bottom,也能組合成 center top 這樣的寫法;顏色可用 rgb、rgba,若寫 transparent 則為透明。
-moz-linear-gradient(center top, transparent, transparent 49%,
rgba(2,37,58,0.5) 50%, rgba(63,111,135,0.5));
以上是從中上方開始、在 49% 到 50% 之間做一次突兀的顏色切換,藉此做出分界線的效果。
-webkit-gradient(linear, center top, center bottom,
from(transparent),
color-stop(49%, transparent),
color-stop(50%, rgba(2,37,58,0.5)),
to(rgba(63,111,135,0.5)));
-o-linear-gradient(top, transparent, transparent 49%,
rgba(2,37,58,0.5) 50%, rgba(63,111,135,0.5));
寫法為「起點 y、終點 x」:
-webkit-gradient(linear, 0% 100%, 100% 100%,
from(#517384), color-stop(50%, #79a3b8), to(#517384));
-moz-linear-gradient(center left,
rgba(81,115,132,0.55), rgba(121,163,184,0.55) 50%,
rgba(81,115,132,0.55));
上面這幾套私有語法在今日已無必要。現代瀏覽器可直接使用標準寫法:
background: linear-gradient(to bottom,
rgba(255,255,255,0) 0%,
rgba(255,255,255,0) 49%,
rgba(2,37,58,0.5) 50%,
rgba(63,111,135,0.5) 100%);
方向寫法從「起始點」改成了「to + 方向」,例如 to bottom、to right、to top left,語意比舊版的座標直覺得多。若還要支援很舊的環境,才需要在其上方補上帶前綴的版本,並把標準寫法放在最後一行,讓支援的瀏覽器優先採用標準語法。
另外提醒:漸變是 background 的一部分,若元素同時有其他背景層,記得用 background-image 搭配 background-color 分開宣告,較不容易出錯。