background 扩展属性详解

background 简写

多图片模式下的写法:

background: url(a.png) top left no-repeat,
    url(b.png) center / 100% 100% no-repeat,
    url(c.png) white;

以前没有那么多新增属性的时候,简写就是:

background: url(a.png) top left no-repeat fixed #000;

后面多了css3后就应该是

background: url(a.png) top left / cover no-repeat fixed content-box content-box #000

其格式就是:

background: <bg-image> || <position> [ / <bg-size> ]? || <repeat-style> || <attachment> || <box> || <box> || <'background-color'>

上文里的 <box> 可能出现 0 次、1 次或 2 次。如果出现 1 次,它同时设定 background-origin 和 background-clip。如果出现 2 次,第一次的出现设置 background-origin,第二次的出现设置 background-clip。

总之background 属性在 css3 时扩展了

  • background-size
  • background-origin
  • background-clip

background-size

参见 MDN

/* 关键字 */
background-size: cover
background-size: contain

/* 一个值: 这个值指定图片的宽度,图片的高度隐式的为auto */
background-size: 50%
background-size: 12px

/* 两个值 */
/* 第一个值指定图片的宽度,第二个值指定图片的高度 */
background-size: 50% auto

  • auto 以背景图片的比例缩放背景图片。
  • cover 缩放背景图片以完全覆盖背景区,可能背景图片部分看不见
  • contain 缩放背景图片以完全装入背景区,可能背景区部分空白

background-origin

参见 MDN

注意:当使用 background-attachment 为fixed时,该属性将被忽略不起作用。

<box> = border-box | padding-box | content-box

background-clip

参见 MDN

background-attachment

参见 MDN

background-attachment: scroll;
background-attachment: fixed;
background-attachment: local;
  • fixed 此关键字表示背景相对于视口固定。即使一个元素拥有滚动机制,背景也不会随着元素的内容滚动。
  • local 此关键字表示背景相对于元素的内容固定。如果一个元素拥有滚动机制,背景将会随着元素的内容滚动, 并且背景的绘制区域和定位区域是相对于可滚动的区域而不是包含他们的边框。
  • scroll 此关键字表示背景相对于元素本身固定, 而不是随着它的内容滚动(对元素边框是有效的)。

利用 attachment 可以制造视差滚动效果,见我的博客 background-attachment 制造视差滚动效果案例

posted @ 2020-04-07 12:03  Ever-Lose  阅读(437)  评论(0编辑  收藏  举报