background-attachment

**background-attachment** CSS 属性设置背景图像的位置是固定在视口中,还是与其包含块一起滚动。

试试看

语法

css
/* Keyword values */
background-attachment: scroll;
background-attachment: fixed;
background-attachment: local;

/* Global values */
background-attachment: inherit;
background-attachment: initial;
background-attachment: revert;
background-attachment: revert-layer;
background-attachment: unset;

background-attachment 属性指定为以下列表中的关键字值之一。

fixed

背景相对于视口固定。即使元素具有滚动机制,背景也不会随元素移动。

local

背景相对于元素的内容固定。如果元素具有滚动机制,则背景会随元素的内容一起滚动,并且背景绘制区域和背景定位区域相对于元素的可滚动区域,而不是相对于围绕它们的边框。

scroll

背景相对于元素本身固定,并且不会随其内容滚动。(它实际上附加到元素的边框上。)

正式定义

初始值scroll
应用于所有元素。它也适用于::first-letter::first-line
继承
计算值如指定
动画类型离散

正式语法

background-attachment = 
<attachment>#

<attachment> =
scroll |
fixed |
local

示例

简单示例

HTML

html
<p>
  There were doors all round the hall, but they were all locked; and when Alice
  had been all the way down one side and up the other, trying every door, she
  walked sadly down the middle, wondering how she was ever to get out again.
</p>

CSS

css
p {
  background-image: url("starsolid.gif");
  background-attachment: fixed;
}

结果

多个背景图像

此属性支持多个背景图像。您可以为每个背景指定不同的<attachment>,用逗号分隔。每个图像都与相应的<attachment>类型匹配,从第一个指定到最后一个。

HTML

html
<p>
  There were doors all round the hall, but they were all locked; and when Alice
  had been all the way down one side and up the other, trying every door, she
  walked sadly down the middle, wondering how she was ever to get out again.
  Suddenly she came upon a little three-legged table, all made of solid glass;
  there was nothing on it except a tiny golden key, and Alice's first thought
  was that it might belong to one of the doors of the hall; but, alas! either
  the locks were too large, or the key was too small, but at any rate it would
  not open any of them. However, on the second time round, she came upon a low
  curtain she had not noticed before, and behind it was a little door about
  fifteen inches high: she tried the little golden key in the lock, and to her
  great delight it fitted!
</p>

CSS

css
p {
  background-image: url("starsolid.gif"), url("startransparent.gif");
  background-attachment: fixed, scroll;
  background-repeat: no-repeat, repeat-y;
}

结果

规范

规范
CSS 背景和边框模块级别 3
# the-background-attachment

浏览器兼容性

BCD 表格仅在浏览器中加载

另请参阅