一、什么是background背景铺满
当我们给网页设置一个背景图或背景色时,如果这张背景图或背景色不能够填满整个网页,就会出现下面这样的情况:
body {
background: url(bg.jpg) repeat;
}
而background背景铺满就是指让背景色或背景图自动缩放铺满整个网页,不留任何空隙。
二、如何设置background背景铺满
通过CSS中background-size属性即可设置背景图的伸缩方式,该属性有两个常用的取值:
1. cover
该值会保持背景图像的纵横比并将图像缩放到最大尺寸以适应其容器。背景图像的某些部分可能无法显示在容器中
body {
background: url(bg.jpg) no-repeat center center fixed;
background-size: cover;
}
2. contain
该值会保持背景图像的纵横比并将图像缩放到最大尺寸以适应其容器,但是背景图像的所有部分都应在容器中可见。
body {
background: url(bg.jpg) no-repeat center center fixed;
background-size: contain;
}
三、进阶应用
1. 设置背景图居中
可以通过对background-position属性进行设置:
body {
background: url(bg.jpg) no-repeat center center fixed;
background-size: cover;
background-position: center center;
}
2. 背景图固定
通过设置background-attachment属性即可实现背景图固定,该属性有两个常用取值:
1. scroll
背景图片滚动,即当作普通的网页滚动处理
body {
background: url(bg.jpg) no-repeat center center scroll;
background-size: cover;
background-position: center center;
}
2. fixed
背景图片固定不动,即当作页面的背景处理
body {
background: url(bg.jpg) no-repeat center center fixed;
background-size: cover;
background-position: center center;
}
3. 动态背景
可以通过改变transition、animation等CSS属性实现动态背景,这里以CSS3的animation为例:
@keyframes example {
from {background-color: #fff;}
to {background-color: #000;}
}
body {
animation-name: example;
animation-duration: 4s;
animation-direction: alternate;
animation-iteration-count: infinite;
}
四、总结
通过background-size属性可以轻松实现background背景铺满,而通过background-position、background-attachment等属性的设置,可以使背景图像更加美观、完整。而动态背景则可以为网页增添生动感、节奏感。
版权声明:本文为luotaif原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。