开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 2 天,点击查看活动详情
之前自己写了一个服装商城,然后用到了这个属性,觉得还蛮酷的,然后这里详细记录下这个属性。
background-attachment
background-attachment 的作用是设置背景图片是随滚动轴如何滚动的css属性,前提是定义了 background-image 属性。
属性:
scroll默认值,背景图相对于元素固定,背景随页面滚动而移动,即背景和内容绑定。local背景图相对于元素内容固定。fixed背景图相对于视口固定,所以随页面滚动背景不动,相当于背景被设置在了body上。inhert就是单纯地继承父元素的属性。
scroll
背景图是相对于元素自身固定,内容动时背景图也动。
栗子↓
.background {
background-image: url('./static/clothes.jpg');
background-repeat: no-repeat;
background-size: cover;
background-attachment: scroll;
}
<div class="container">
<div class="background"></div>
<p class="text">background-attachment ......</p>
</div>
local
这个和 scroll 作用差不多,区别是,假如这个元素内部设置了overflow:scroll,那么background-attachment 设置了 scroll 的话,背景图片不会随着内部滚动条的滚动而滚动,但是假如设置了 local,那么内容就会随着滚动条的滚动而滚动。直接看效果叭↓
1. 设置 background-attachment:scroll
.background {
background-attachment: scroll;
overflow: auto;
}
<div class="container">
<div class="background">background-attachment ......</div>
</div>
2. 设置 background-attachment:local
.background {
background-attachment: local;
overflow: auto;
}
<div class="container">
<div class="background">background-attachment ......</div>
</div>
准确来讲,
scroll相对于元素固定,而local是相对于元素内容固定。也就是说,在存在内部滚动条的情况下,scroll就相当于fixed,而local就相当于scroll。
fixed
背景图片相对于视口固定,就算元素有了滚动条,背景图也不随内容移动。
.background {
background-image: url('./static/clothes.jpg');
background-repeat: no-repeat;
background-size: cover;
background-attachment: fixed;
}
<div class="container">
<div class="background"></div>
<p class="text">background-attachment ......</p>
</div>
fixed设置后,与scroll的背景图片位置相对于元素不同,fixed的背景图片位置是相对于页面可视区域的左上角的,元素的大小是背景图片能够显示的范围,当滚动过了这个范围,背景图片也将无法看见。fixed不会随着滚动条的滚动而滚动,它只会固定在页面中的某一个位置。