如何使用rgba覆盖父元素以及如何覆盖子图像

时间:2019-02-18 10:28:13

标签: html css

#parent{
  background: rgba(0,0,0,0.4)
}

img{
  margin: 0 auto;
  display: block;
  position: relative;
  width: auto;
  max-width: 100%;
}
<div id="parent">
<div>I am text</div>
<div>
<img src="https://images.pexels.com/photos/67636/rose-blue-flower-rose-blooms-67636.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260"/>
</div>
<div>

如您所见,尽管图像的父级设置了rgba透明度,但图像并未被覆盖。但是,我希望图像具有与父图像相同的叠加层。我该如何克服呢? (我需要IE 10、11兼容性)

2 个答案:

答案 0 :(得分:2)

这是您想要的吗?

img{
  margin: 0 auto;
  display: block;
  width: auto;
  max-width: 100%;
}

.image {
  position: relative;
}

.image:before {
  content: "";
  position: absolute;
  top:0;
  bottom:0;
  left:0;
  right:0;
  background-color: rgba(0, 0, 0, 0.6);
  z-index: 99;
}
<div id="parent">
    <div>I am text</div>
  <div class="image">
  <img src="https://images.pexels.com/photos/67636/rose-blue-flower-rose-blooms-67636.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260"/>
  </div>
<div>

JSFiddle example

答案 1 :(得分:0)

在CSS下方使用此代码:

    #parent::before{
  background: rgba(0,0,0,0.6);
  content:"";
    display: block;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    z-index: 2;
}
#parent{
    position: relative;
}

img{
  margin: 0 auto;
  display: block;
  position: relative;
  width: auto;
  max-width: 100%;
}
        <div id="parent">
                <div>I am text</div>
                <div>
                <img src="https://images.pexels.com/photos/67636/rose-blue-flower-rose-blooms-67636.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260"/>
                </div>
        </div>