• 前端如何通过linear-gradient()函数实现颜色渐变效果
  • 发布于 2个月前
  • 152 热度
    0 评论
前端可以通过linear-gradient()函数用于实现设置创建多种颜色实现的线性渐变的图片,基本上所有可以设置图片资源的属性均适合使用,可以将其视为一种特别的图片样式。函数设置格式如下:
// 语法格式
linear-gradient(
  [ <angle> | to <side-or-corner> ,]? <color-stop-list> )
  \---------------------------------/ \----------------------------/
    Definition of the gradient line        List of color stops

where <side-or-corner> = [ left | right ] || [ top | bottom ]
  and <color-stop-list> = [ <linear-color-stop> [, <color-hint>? ]? ]#, <linear-color-stop>
  and <linear-color-stop> = <color> [ <color-stop-length> ]?
  and <color-stop-length> = [ <percentage> | <length> ]{1,2}
  and <color-hint> = [ <percentage> | <length> ]

// 使用示例
/* 渐变轴为45度,从蓝色渐变到红色 */
linear-gradient(45deg, blue, red);

/* 从右下到左上、从蓝色渐变到红色 */
linear-gradient(to left top, blue, red);

/* 从下到上,从蓝色开始渐变、到高度 40% 位置是绿色渐变开始、最后以红色结束 */
linear-gradient(0deg, blue, green 40%, red);
浏览器兼容性

linear-gradient()属于标准用法,一般需要浏览器有较高的版本。对于较低版本浏览器的兼容性使用规则如下:
<!--标准用法 -->
linear-gradient( [ [ <angle> | [top | bottom] || [left | right] ],]? <color-stop>[, <color-stop>]+);
-webkit-gradient(<type>, <point> [, <radius>]?, <point> [, <radius>]? [, <stop>]*)
-moz-linear-gradient([ [ [top | bottom] || [left | right] ],]? <color-stop>[, <color-stop>]+);
-o-linear-gradient(<type>, <point> [, <radius>]?, <point> [, <radius>]? [, <stop>]*)
-webkit前缀的支持 Chrome 25 和 Safari 6,iOS 6.1,Android 4.3
-moz前缀的支持Firefox (3.6 to 15) 版本
-o前缀的支持Opera (11.1 to 12.0) 版本
-webkit-gradient最初语法中,使用同样的语法实现线性渐变和径向渐变。但这两种渐变所需要的参数有所不同,导致了需要增加第一个参数来区分两种渐变。如果再增加渐变类型,这样的处理方式会变得更加复杂。比如锥形渐变,需要用到函数和不规范的 CSS 值。

-moz-linear-gradient这个语法它只允许水平和垂直渐变。

代码示例
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>堆代码 duidaima.com</title>
    <style>
        #grad1 {
            height: 200px;
            background-color: red;
            /* 不支持线性的时候显示 */
            background-image: linear-gradient(45deg, red, orange, yellow, green, blue, indigo, violet);
        }
    </style>
</head>
<body>
    <h3>线性渐变 - 渐变轴从左上角出发并且呈 45 度</h3>
    <p>渐变轴上定义了:red、orange、yellow、green、blue、indigo、violet颜色</p>
    <div id="grad1"></div>
    <p><strong>注意:</strong> Internet Explorer 8 及之前的版本不支持渐变。</p>
</body>

</html>

用户评论