漸變之linear-gradient


對於前端開發人員來說,漸變是很多時候都會用到的。在以前,漸變效果和陰影、圓角效果依靠代碼來寫是比較男的,一般都是做成圖片,直接編寫  CSS 代碼就可以實現。今天小編為大家講解CSS3中的linear-gradient()函數來寫漸變。

如果說到漸變大家都會想到CSS3里面的linear-gradient()函數,看了文檔就知道怎么簡單的做一個漸變效果如下圖:

然而我們真正了解linear-gradient()這個函數嗎?為什么用在background里有效而用在

background-color里面卻沒有效果?

首先我們明確一點linear-gradient函數創建的是一個顏色線性漸變的圖片,所有的線性漸變都不不是顏色。然而它是什么樣的一個圖片呢?顯然它不像jpeg有固定尺寸,也不像多個固定尺寸的.ico.也不像尺寸比例的圖像比如SVG格式,實際上它是既沒有固定尺寸大小也沒有高寬比列的圖形,它具體的尺寸其實是適用的元素的尺寸,所以linear-gradient只能使用在使用圖片的屬性里。

通過漸變新舊語法不同看屬性(環境:谷歌瀏覽器最新版本):

舊式寫法:

-webkit-gradient(<type>, <point> [, <radius>]?, <point> [, <radius>]? [, <stop>]*)

第一個參數設置Type:linear或者radial

第二/三個參數設置漸變位置的起點/結束點:坐標形式、關鍵值兩種表示比如 left top(左上角)和left bottom(左下角)

第四/五個參數設置漸變色點位置和顏色:通過color-stop函數,函數第一個參數設置漸變位置(比如:0為起點,0.5為中點,1為結束點),第二個參數設置顏色

新式寫法:

-webkit-linear-gradient( [<point> || <angle>,]? <stop>, <stop> [, <stop>]* )

第一個值設置:漸變位置(可以使用關鍵值(left,top..)和deg兩種方式)

第二個、三個值:設置漸變點的位置和顏色

通過demo來看老式與新式寫法的差異與屬性值之間的差異:

background:-webkit-gradient(linear,center top,center bottom,from(yellow), to(red));
background: -webkit-linear-gradient(top,yellow,red);

總結:老式寫法設置漸變位置是通過兩個關鍵值確定,而新的寫法使用一個關鍵值即可,

demo2

background: -webkit-gradient(linear, left top, right top, from(red), color-stop(0.25, yellow),
            color-stop(0.5, red), color-stop(0.75, yellow), to(red));
background: -webkit-linear-gradient(left, red, yellow 25%, red 50%, yellow 75%, red);

background:-webkit-gradient(linear,center top,center bottom,color-stop(0.6,red), to(yellow));
background: -webkit-linear-gradient(top,red 60%, yellow);

總結:設置多種顏色漸變點的位置老式使用color-stop函數,新式直接指定百分比

通過demo來看新式寫法漸變位置關鍵值與度之間的差異:

background: -webkit-linear-gradient(360deg,red 60%, yellow) ;
background: -webkit-linear-gradient(0deg,red 60%, yellow) ;
background: -webkit-linear-gradient(left,red 60%, yellow) ;
left-->360deg/0deg

background: -webkit-linear-gradient(270deg,red 60%, yellow) ;
background: -webkit-linear-gradient(top,red 60%, yellow) ;
top-->270deg

background: -webkit-linear-gradient(180deg,red 60%, yellow) ;
background: -webkit-linear-gradient(right,red 60%, yellow) ;
right-->180deg

background: -webkit-linear-gradient(90deg,red 60%, yellow) ;
background: -webkit-linear-gradient(bottom,red 60%, yellow) ;
bottom-->90deg

希望通過這篇文章讓大家對linear-gradient有進一步的了解。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM