CSS中经常用到背景图,但有时需要避免同一张背景图重复出现在多个元素中,这便需要使用不重复背景图。
.selector-1 {
background-image: url(image.jpg);
background-repeat: no-repeat;
}
.selector-2 {
background-image: url(image.jpg);
background-repeat: no-repeat;
background-position: center;
}
.selector-3 {
background-image: url(image.jpg);
background-repeat: no-repeat;
background-position: right bottom;
} 以上代码是实现不重复背景图的三种方式:
.selector-4 {
position: relative;
z-index: 1;
}
.selector-4:before {
content: "";
display: block;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-image: url(image.jpg);
background-repeat: no-repeat;
z-index: -1;
} 以上代码中,我们使用伪类:before在.selector-4中创建一个占满整个元素的背景,这样就避免了在HTML中增加额外的代码。