Skip to content

CSS3 渐变

CSS3 渐变(gradients)可以让你在两个或多个指定的颜色之间显示平稳的过渡。以前,你必须使用图像来实现这些效果。现在,使用 CSS3 渐变(gradients),通过代码来实现渐变可以减少请求和节约带宽。

CSS3 定义了两种类型的渐变(gradients):

渐变实际上不是背景颜色,而是背景图片:

用background-image/background

background包括了background-color和background-image

image-20220407202735622

1.线性渐变(Linear Gradients)

  • 向下/向上/向左/向右/对角方向

background: linear-gradient(direction, color-stop1, color-stop2, ...);

css
/*欧朋 opera */
background-image:-o-linear-gradient(red,green,yellow,blue,orange);
/*chrome safari */
background-image:-webkit-linear-gradient(red,green,yellow,blue,orange);
/*火狐浏览器*/
background-image:-moz-linear-gradient(red,green,yellow,blue,orange);
/*标准的*/
background-image:linear-gradient(red,green,yellow,blue,orange);

与下面等效:

css
background: linear-gradient(red,green,yellow,blue,orange);

加方向:从下到上

css
background: linear-gradient(to top,blue,yellow);

加角度:0deg = to top (deg是度数的意思)

45度,向右上

css
background: linear-gradient(45deg,blue,yellow);

等价于下面:向右上

css
background: linear-gradient(to right top,blue,yellow)

重复设置线性渐变:这时要加比例才有效果

css
background:repeating-linear-gradient(blue 20%,yellow 40%);

2.径向渐变(Radial Gradients)

  • 由它们的中心定义

​ background: radial-gradient(center, shape, size, start-color, ..., last-color);

​ 默认情况下,渐变的中心是 center(表示在中心点),渐变的形状是 ellipse(表示椭圆形)

​ shape可以是值 circle 或 ellipse。其中,circle 表示圆形,ellipse 表示椭圆形

css
<style>
    #box1{
        width:200px;
        height:300px;
        border:1px solid red;
        margin: 100px auto;
        background: radial-gradient(at 20% 20% closest-corner circle,blue,yellow);
        /*四个参数:前三个参数没有顺序,但是中间不能加逗号
            中心点(at center center)
                语法:(at x y )都是从左上角原点为参考点
                x,y 可以是像素10px 20px,也可以是百分比 10% 20%
            大小(扩散到哪个位置,决定了这个扩散效果有多大)
                最近边 closest-side
                最远边 farthest-side
                最近角 closest-corner
                最远角 farthest-corner
            形状
                ellipse 椭圆 默认值
                circle 圆
            颜色
                从里向外的扩散颜色分别是什么
        */
    }