【问题标题】:align the background-image of :after to its parent container将 :after 的背景图像与其父容器对齐
【发布时间】:2014-05-31 08:04:15
【问题描述】:

我想在我的内容 div 中获得一个透明的背景图像。为了在不影响 .content 的子元素的情况下执行此操作,我定义了 .content:after 的背景图像,并希望将其位置设置为我的 .content 的位置。

问题是:在这段代码中,背景图像从top: 0, left: 0, right: 0, bottom: 0 body开始。我怎样才能让它从我的 .content 开始?另一个问题是我实际上也有一个高度灵活的标题。所以不知道 .content 的绝对置顶位置。

.content {
  width: 200px;
  margin: 10px auto;
}
.content:after {
  content: "";
  background-image url("http://works.mihaimoga.com/stackoverflow_logo.jpg");
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  opacity: 0.7;
}

【问题讨论】:

标签: html css background-image opacity


【解决方案1】:

除了使用:after 伪类,您可以使用背景值作为rgba。这不会影响子元素的透明度。

.content {
    width: 200px;
    margin: 10px auto;
    background-image url("http://works.mihaimoga.com/stackoverflow_logo.jpg");
    background-color: rgba(255, 255, 255, 0.7);  /* added */
}

【讨论】:

  • @Jere 你删除了:after 样式吗?
  • @Jere 如果我的解决方案不起作用.. 删除我的样式并尝试将position: relative 添加到.content 并保留:after 样式。让我知道结果。
  • @Jere 尝试将z-index 提供给:after 伪类。
【解决方案2】:

.content div 设置为position: relative,将.content:after 设置为position: absolute。确保应用正确的z-indexes.content:after 的 z-index 应该高于 .content

应该是这样的:

.content {
  width: 200px;
  margin: 10px auto;
  position: relative;
  z-index: 10;
}
.content:after {
  content: "";
  background-image url("http://works.mihaimoga.com/stackoverflow_logo.jpg");
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  opacity: 0.7;
  z-index: 20;

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-04
    • 2011-10-20
    • 2020-10-07
    • 1970-01-01
    • 2014-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多