首页 话题 小组 问答 好文 用户 我的社区 域名交易 唠叨

[分享]css不重复背景图

发布于 2024-11-11 19:07:25
0
12

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;
} 

以上代码是实现不重复背景图的三种方式:

  • 不同的选择器使用不同的背景位置:通过将不同的元素使用不同的选择器,并且设置不同的背景位置,使得同一张背景图在不同的元素中展示出不同的部分。
  • 背景居中显示:在某些情况下,我们需要将背景图居中显示,这时可以使用background-position:center来实现。
  • 使用CSS伪类:使用CSS伪类如:before或:after来实现一些有趣的效果,并且避免了在HTML中增加额外的代码。例如:
.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中增加额外的代码。

评论
一个月内的热帖推荐
91云脑
Lv.1普通用户

62849

帖子

14

小组

291

积分

赞助商广告
站长交流