漸變(gradients)可以讓我們在兩個或多個顏色之間進行平穩的過渡。
曾經我們只有使用圖像來實現顏色的過渡效果,但漸變的出現,可以讓用戶使用時減少下載的時間和寬帶的使用。
漸變效果的元素在放大時看起來效果會更好,這是因為漸變是由瀏覽器自己生成的。
漸變分為線性漸變和徑向漸變。
線性漸變(LinearGradients):向下/向上/向左/向右/對角方向
徑向漸變(RadialGradients):由它們的中心定義
IE9及以下不兼容
線性漸變語法:background-image:linear-gradient(direction,color-stop1,color-stop2,...);
direction:可選,方向
color:顏色,至少要寫兩個,可以寫多個
比如:
/*totop、tobottom、toleft、toright、tolefttop等等*//*xxxdegdeg表示度數*//*可以同時指定多個顏色,多個顏色默認情況下平均分配也可以手動指定漸變的分布情況*//*從上往下,紅色漸變到黃色*/linear-gradient(red,yellow);/*從右下往左上、從紅色漸變到黃色*/linear-gradient(tolefttop,red,yellow);/*漸變角度為45度,從藍色漸變到紅色*/linear-gradient(45deg,red,yellow);/*從下往上,從紅色開始漸變、到高度40%時開始由藍色漸變、最後以黃色結束*/linear-gradient(0deg,red,blue40%,yellow);不設置direction不寫方向顏色默認是從上往下過渡<style>div{width:200px;height:100px;background-image:linear-gradient(red,yellow);}</style><body><h3>顏色漸變:從上往下</h3><div></div></body>多個顏色<style>div{width:200px;height:100px;background-image:linear-gradient(red,pink,blue);}</style><body><div></div></body>設置direction1.用to去指明要漸變的方向線性漸變-從左到右<style>div{width:200px;height:100px;background-image:linear-gradient(toright,red,yellow);}</style><body><h3>顏色漸變:從左往右</h3><div></div></body>線性漸變-對角<style>div{width:200px;height:100px;background-image:linear-gradient(torightbottom,red,yellow);}</style></head><body><h3>顏色漸變:從左往右下</h3><div></div></body>2.設置角度角度是指水平線和漸變線之間的角度,在0deg將創建壹個從下到上的漸變,90deg將創建壹個從左到右的漸變。
有些舊瀏覽器顯示的是:0deg將創建壹個從左到右的漸變,90deg將創建壹個從下到上的漸變。
我們可以使用換算公式:x=90-y,其中x為標準角度,y為非標準角度。
<style>div{float:left;margin:5px;width:200px;height:100px;/*0deg默認是從下往上*/background-image:linear-gradient(0deg,red,yellow);}.one{/*90deg從左往右*/background-image:linear-gradient(90deg,red,yellow);}.two{/*180deg從上往下*/background-image:linear-gradient(180deg,red,yellow);}.three{/*-90deg從右往左*/background-image:linear-gradient(-90deg,red,yellow);}.four{/*-90deg指定顏色分配從右往左*/background-image:linear-gradient(-90deg,red,blue40%,yellow);}</style><body><div></div><divclass="one"></div><divclass="two"></div><divclass="three"></div><divclass="four"></div></body>使用透明度使用透明度的操作和上面還是壹樣的,只是把顏色變成了透明效果。
<style>div{margin:5px;width:200px;height:100px;/*紅色,透明度逐漸增大*/background-image:linear-gradient(toright,rgba(255,0,0,0),rgba(255,0,0,1));}.one{background-image:linear-gradient(toright,transparent,rgba(255,0,0,1));}</style><body><h3>顏色漸變:從左往右</h3><div></div><divclass="one"></div></body>重復的線性漸變語法:background-image:repeating-linear-gradient(direction,color1,color2,...);
重復的線性漸變和不重復的線性漸變壹樣,只是需要手動指定顏色分配,這樣才會出現重復樣式。
<style>div{float:left;margin:5px;width:200px;height:100px;/*默認是上往下*/background-image:repeating-linear-gradient(red,yellow20%);}.one{/*多個顏色*/background-image:repeating-linear-gradient(red,blue20%,yellow40%);}.two{/*指定方向,從左往右*/background-image:repeating-linear-gradient(toright,red,yellow20%);}.three{/*指定顏色分配從左往右*/background-image:repeating-linear-gradient(90deg,red,blue30%,yellow40%);}</style><body><div></div><divclass="one"></div><divclass="two"></div><divclass="three"></div></body>原文:/post/7099048020490059812