iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 26
1
Modern Web

前端路上那些重要與不重要的小事系列 第 26

Day26:小事之 多重背景與漸層背景 CSS3 Gradients

多重背景與漸層背景是 CSS3 才開始有的背景屬性

瀏覽器適用前綴

Google Chrome 與 Apple Safari 使用 -webkit-
Mozilla FireFox 使用 -moz- 
Opera 使用 -o-
(實測結果 Mac 的 FireFox 也吃 -webkit-)

瀏覽器的支援度

背景的基礎寫法

以下是背景的簡寫寫法

background: 顏色 url() repeat position;
background: #333 url(images/firefox.png) no-repeat left bottom;

拆開來的獨自寫法為

background-image: url(images/firefox.png);
background-position: left bottom;
background-origin: border-box;
background-repeat: no-repeat;

一般在寫 background 我會習慣寫簡寫,比較快速XD

線性漸層 linear-gradient

還沒有 CSS3 之前,想要有線性漸層只能做一張細細長長的背景圖,利用 background-repeat 的屬性去做重複背景。現在有 CSS3 了,做漸層背景,想要換顏色可以隨時換掉,想調整角度只要改個數值就好,真的是方便無敵多。

background: linear-gradient(顏色漸變方向<開始方向 結束方向>, 色碼1 位置1,色碼2 位置2,....)

- 顏色漸變方向,預設值為由上而下 linear-gradient(yellow,red)
- 由左而右的線性漸層效果 
    - background: -webkit-linear-gradient(left,yellow,red);
    - background: -o-linear-gradient(right,yellow,red);
    - background: -moz-linear-gradient(right,yellow,red);
    - background: linear-gradient(to right,yellow,red);
- 對角線的線性漸層效果(由左下向右上)
    - background: -webkit-linear-gradient(left top,yellow,red);
    - background: -o-linear-gradient(bottom right,yellow,red);
    - background: -moz-linear-gradient(bottom right,yellow,red);
    - background: linear-gradient(to bottom right,yellow,red);
- 利用角度調整的線性漸層效果
    - background: linear-gradient(90deg,yellow,red);

如果背景需要有圖片加上漸層背景,要先寫圖片,再寫漸層,如果寫相反,圖片會被漸層蓋住。而圖片與漸層 或 漸層與漸層中間用逗號 , 分開。

.box{
  background: url(https://mdn.mozillademos.org/files/11305/firefox.png) no-repeat bottom,
    -webkit-linear-gradient(top, purple, white);
}

漸層顏色後面可以加上位置,形成銳利的直線。

.box{
  background: -webkit-linear-gradient(left bottom,blue 50%,lightgreen 50%);
}//後面的百分比就是漸層的位置,這樣可以造成銳利的直線。

圓形(徑向)漸層 radial-gradient

ellipse為橢圓、circle為圓形,而在其後,寫在越前面的顏色為越靠近中心點的顏色。

background: radial-gradient(ellipse 或 circle,顏色1,顏色2, ......);

.box{
  background: radial-gradient(ellipse,#fff,#ccc,#999,#666,#333,#000);
  //ellipse橢圓形,circle為圓型
}

試玩範例

以上是今天介紹的 CSS 漸層,各位看倌明天見囉~

參考資料:
[1] CSS Backgrounds - w3.org
[2] CSS3 多重背景


上一篇
Day25:小事之 CSS 偽元素 與 content Property
下一篇
Day27:小事之 Transition 與 Animation
系列文
前端路上那些重要與不重要的小事30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言