先看下实例
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>css背景图片固定</title>
<style>
body{
background-image: url("https://picsum.photos/id/100/1080/1400");
background-repeat: no-repeat;
background-attachment: fixed;
background-position: center 0%;
}
h3{line-height: 500px;text-align: center}
</style>
</head>
<body style="height: 3000px">
<h3>背景图片固定,页面滚动不影响</h3>
</body>
</html>有时项目中会遇到背景图固定,页面内容可以滚动,背景不随页面滚动而滚动。就像QQ空间、微博设置自定义背景图的固定选项。
其实很容易实现,利用 background-attachment:fixed; 就能实现,代码如下:
body{
background: url("bg.png");
background-repeat: no-repeat;
background-attachment:fixed;
}