在CSS中,我们可以使用background-attachment属性来定义背景图片是随元素一起滚动还是固定不动。

语法:

background-attachment: 取值;

说明:

background-attachment属性取值只有2个,如下表所示。

表1 background-attachment属性取值
属性值 说明
scroll 随元素一起滚动(默认值)
fixed 固定不动

举例:

<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <style type="text/css"> div { width:160px; height:1200px; border:1px solid silver; background-image:url(img/judy.png); background-repeat:no-repeat; background-attachment:fixed; } </style> </head> <body> <div></div> </body> </html>

浏览器预览效果如下图所示。

分析:

我们在本地浏览器中拖动右边的滚动条会发现,背景图片在页面固定不动了。如果把background-attachment:fixed;这一行代码去掉,背景图片就会随着元素一起滚动。

在实际开发中,background-attachment这个属性几乎用不上,这里看一下就行。