背景附着与简写
fixed/scroll 背景固定、background 简写属性一行搞定
背景附着与简写
background-attachment 控制背景图是否随页面滚动,简写属性一行搞定所有背景设置。
学完本章你将: 掌握 fixed/scroll 背景固定、background 简写。
背景附着
css
/* scroll:背景随元素滚动(默认) */
.scroll-bg {
background-image: url("bg.jpg");
background-attachment: scroll;
}
/* fixed:背景固定——视差效果 */
.parallax {
background-image: url("bg.jpg");
background-attachment: fixed; /* 背景不动,内容动 */
height: 500px;
}
/* local:背景随内容滚动 */
.local-bg {
background-attachment: local; /* 内容滚动时背景跟着动 */
}
经典视差效果
html
<div class="parallax">第一节</div>
<div class="content">内容区域</div>
<div class="parallax">第二节</div>
css
.parallax {
background-image: url("bg.jpg");
background-attachment: fixed;
background-size: cover;
background-position: center;
height: 400px;
}
background 简写
css
/* 全写 */
.box {
background-color: #f0f0f0;
background-image: url("bg.png");
background-repeat: no-repeat;
background-position: center;
background-size: cover;
background-attachment: fixed;
}
/* 简写一行搞定(推荐) */
.box {
background: #f0f0f0 url("bg.png") no-repeat center/cover fixed;
}