css background 背景

css background-attachment 属性 设置背景图像是否固定或者随着页面的其余部分滚动。

可简单理解为定义背景图片随滚动轴的移动方式。

语法

background-attachment: value;
其中value可能的值为:
  • scroll:默认值,背景图相对于元素固定,背景随页面滚动而移动,即背景和内容绑定。
  • fixed:背景图相对于视口固定,所以随页面滚动背景不动,相当于背景被设置在了body上。
  • local:背景图相对于元素内容固定,
  • inhert:继承。

例子

1.fixed 

fixed就是固定的意思,意思页面滚动,背景图不动,相当于背景被设置在了body上。

<!DOCTYPE html>
<html>
<title>css background-attachment属性例子fixed</title>
<head>
<style>
div
{
   color:#fff;
   width:300px;
   height:1024px;
   background-image: url(/static/default/yxjc/css/good-morning.jpg) ;
   background-repeat: no-repeat;
   background-attachment: fixed;
}
</style>
</head>
<body>
<div>
	css background-attachment
</div>
</body>
</html>

动图效果:

我们看到当页面下拉的过程中,css background-attachment 文字已经看不到了,但是背景图还是不动的。

css background-attachment 属性

2. local

滚动元素的时候,背景图也会随之变动。

<!DOCTYPE html>
<html>
<title>css background-attachment属性例子local</title>
<head>
<style>
div
{
   color:#fff;
   width:300px;
   height:1024px;
   background-image: url(/static/default/yxjc/css/good-morning.jpg) ;
   background-repeat: no-repeat;
   background-attachment: local;
}
</style>
</head>
<body>
<div>
	css background-attachment
</div>
</body>
</html>
动图效果如图所示:

我们看到当页面下拉的过程中,css background-attachment 文字和背景图都看不到了。

css background-attachment 属性