linear-gradient是css3中background新增的背景属性,可以用来实现一种线性渐变的效果。
语法
background:linear-gradient(起点|角度,颜色 位置,颜色 位置,...);
复制代码
起点:to top/right/bottom/left/left top/left bottom/right top/right bottom
角度:逆时针方向 0~360 deg
颜色 位置:red 50%,blue 100% (红色从50%渐变到100%的蓝色)
注意
颜色 位置:这个属性也可以只写颜色
例子
一个简单的从左到右,由红渐变到蓝
<!doctype html>
<html>
<head>
<title>linear-gradient</title>
<style>
.box {
width: 300px;
height: 100px;
margin: 100px auto;
background: linear-gradient(to right, red ,blue);
}
</style>
</head>
<body>
<div class="box"></div>
</body>
</html>
复制代码
运行结果:
带颜色位置的例子
<!doctype html>
<html>
<head>
<title>linear-gradient</title>
<style>
.box {
width: 300px;
height: 100px;
margin: 100px auto;
background: linear-gradient(to right, red 30%,blue 50%, green 100%);
}
</style>
</head>
<body>
<div class="box"></div>
</body>
</html>
复制代码
运行结果:
说明:在该例子中,linear-gradient中有3个颜色位置,(red 30%)表示红色从30%的位置开始渐变,也就是30%之前(包括30%)的都是红色.(blue 50%),这是表示到50%是蓝色,也就是说30%~50%之间是红色到蓝色的渐变,到50%这个位置就是蓝色.接着,(green 100%),表示50%~100%之间是蓝色到绿色的渐变,到100%的时候就是绿色.
从别的方向渐变的例子
从上到下渐变
<!doctype html>
<html>
<head>
<title>linear-gradient</title>
<style>
.box {
width: 300px;
height: 100px;
margin: 100px auto;
background: linear-gradient(to bottom, red, blue);
}
</style>
</head>
<body>
<div class="box"></div>
</body>
</html>
复制代码
运行结果:
使用角度的渐变的例子
<!doctype html>
<html>
<head>
<title>linear-gradient</title>
<style>
.box {
width: 300px;
height: 100px;
margin: 100px auto;
background: linear-gradient(45deg, red, blue);
}
</style>
</head>
<body>
<div class="box"></div>
</body>
</html>
复制代码
运行结果: