CSS渐变之背景、边框、字体渐变

使用CSS实现背景色渐变、边框渐变,字体渐变的效果。

背景色渐变

.bg-block {
  background: linear-gradient(to bottom, #F80, #2ED);
}

效果如图:

linear-gradient: ([ | to , ]? [, + ])

angle | side-to corner 定义了渐变线,to-bottom 等同于180deg, to-top 等同于0deg。
color-stop 定义渐变的颜色,可以使用百分比指定渐变长度。比如:

 background: linear-gradient(180deg, #F80 70%, #2ED);

则变成了酱子:

背景色渐变非常简单,但上面的css代码中,linear-gradient是加在background属性上的。于是测试下具体是加在了哪个属性上,首先感性上就觉得是加在了background-color上,修改代码background为background-color之后,果然,渐变色没有了。
仔细看下linear-gradient的定义:

Thelinear-gradient()function creates an image consisting of a progressive transition between two or more colors along a straight line. Its result is an object of the data type, which is a special kind of []

于是,这应该是个image了,修改代码background为background-image,结果渐变色保持如上图。

字体渐变

字体渐变没那么容易想到了,参考了张鑫旭大神的文章,实现如下:

.font-block {
     font-size: 48px;
     background-image: linear-gradient(to bottom,#F80, #2ED);
     -webkit-background-clip: text;
     -webkit-text-fill-color: transparent;
}

效果如下:

这种字体渐变的方法可以这么理解:字体本身是有颜色的,先让字体本身的颜色变透明(text-fill-color为transparent),然后添加渐变的背景色(background-image: line-gradient...),但是得让背景色作用在字体上(background-clip: text)。

要注意的是:

  • text-fill-color 是个非标准属性,但多数浏览器支持带-webkit前缀,所以使用时需要带上-webkit前缀。
  • background-clip属性虽然多数浏览器已经支持,但text属性值浏览器支持还需要加-webkit前缀。(参考这里:https://developer.mozilla.org...
  • 以上两条,通常使用postcss时是不会自动加前缀的,所以也就不能偷懒。
  • 要注意-webkit-text-fill-color: transparent对字体带来的影响,因为设置了透明,笔者在使用时踩了坑,同时使用了text-overflow: ellipsis; 这个时候是看不到点点点的。

边框渐变

.border-block {
  border: 10px solid transparent;
  border-image: linear-gradient(to top, #F80, #2ED);
  border-image-slice: 10;
}

实现效果如下:

给border-image加linear-gradient不难理解,但是如果单纯使用border-image,会发现效果是这样的:

所以关键作用是border-image-slice属性。

先看下border-image属性。

border-image是border-image-source, border-image-slice, border-image-width, border-image-outset, border-image-repeat的简写。

border-image-source 属性可以给定一个url作为边框图像,类似background-image: url的用法;

border-image-slice是指将边框图片切成9份,四个角四个边,和一个中心区域。被切割的9个部分分布在边框的9个区域。

当盒子宽度和被切图像的宽度不相等时,四个顶角的变化具有一定的拉伸效果。border-image-slice属性默认值是100%,这个百分比是相对于边框图像的宽高来的,当左右切片宽度之和>100%时,5号7号就显示空白,因此使用默认值无法看到被填满的边框图片。关于boder-image具体可以参考这篇References第一篇文章,讲的比较详细。

References

1.CSS3边框图片详解:http://www.360doc.com/content...
2.linear-gradient MDN:
https://developer.mozilla.org...

你可能感兴趣的:(css)