Home  >  Article  >  Web Front-end  >  css3的Background新属性_html/css_WEB-ITnose

css3的Background新属性_html/css_WEB-ITnose

WBOY
WBOYOriginal
2016-06-24 11:38:471109browse

前言

CSS3中出现了几种关于背景图片的新属性:background-origin、background-clip、background-position等.之前大致了解了下,但是background-origin与background-clip的区别尚不清楚。就google了一篇,发现不错,翻译下来吧。
原文连接 : The New Background Position in CSS3
Say Hello to Background-Origin and Background-Clip, CSS3 new features!
ps: 原文在线代码演示已由codepen.io 搬至runjs.cn

background-position

用css给元素设置背景图片的每个人都用过background-position属性,在CSS3之前设置那个位置的值相对于元素的左上角(top,left),例如:

div {background-position: 20px 40px; /* 距左边20px & 距顶部40px */ }

有个问题就是不可能确定相对于其它点的精确位置,例如右下角(bottom, right), 只能以左上角开始。
我们可以写:background-position: right bottom;或者background-position: 70% /* from left */ 80%/* from top */,但不能写出距离右端20px和距离底端20px.

使用新的background-position

为了解决这个问题,CSS3提供了可以定义那个开始的位置和决定原点(0,0)的位置。

工作原理

相对于之前只能赋2个值的情况(相对于left和top的水平和垂直距离),现在用CSS3我们可以指定那个水平和垂直位置的原点,例如right bottom + 值。
background-position: right 20px bottom 40px

Live Example

同时你也能够给一个盒子设置多个背景图片且每个图片的原点不同。

Live Example

background-origin

在CSS2中,当我们给元素添加background-image时,图片是以元素padding的左上角开始。
默认的background-origin位置和设置background-position值为0 left, 0 top一致。我们能够看到background-image以padding开始的。

Live Example

通过background-origin我们能够设置背景图片开始的位置border、padding或content.
- border-box 相对于元素边界的左上角的(0, 0)
- padding-box(default) 相对于元素padding的左上角
- content-box 相对于元素content的左上角。
Live Example

background-clip

在background-origin例子中可以看到,background-origin的背景图片覆盖了元素的border/padding的right/bottom.
使用background-clip可以解决这个问题。使用background-clip我们可以决定裁剪背景图片的位置,值和background-origin的值相同,不过默认是border-box,不裁剪。

Live Example

从background-origin和background-clip的例子中可以看出,大多少情况下可能需要他们一起配合使用。而且使用这些属性可以编写出更nicer的东西,例如:

Live Example

ps:第一次翻译,勉强能看的懂吧。。。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn