How to apply an opacity without affecting a child

2019-01-11 05:45发布

I want to achieve this using html and css:

schema

I have tried to set the opacity of the container to 0.3 and the box to 1, but it doesn't work: both divs have 0.3 opacity.

jsFiddle of my try here

The effect I am trying to achive is a popup box that comes on top of the page. It is highlighted by fading the content below (by lowering the opacity).

标签: html css opacity
8条回答
地球回转人心会变
2楼-- · 2019-01-11 06:46

Try using rgba as a 'pre content' overlay to your image, its a good way to keep things responsive and for none of the other elements to be effected.

header #inner_header_post_thumb {
  background-position: center;
  background-size: cover;
  position: relative;
  background-image: url(https://images.pexels.com/photos/730480/pexels-photo-730480.jpeg?w=1260&h=750&auto=compress&cs=tinysrgb);
  border-bottom: 4px solid #222;
}

header #inner_header_post_thumb .dark_overlay {
  position: relative;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.75);
}

header #inner_header_post_thumb .dark_overlay .container .header-txt {
  padding-top: 220px;
  padding-bottom: 220px;
  color: #ffffff;
  text-align:center;
}

header #inner_header_post_thumb .dark_overlay .container .header-txt h1 {
  font-size: 40px;
  color: #ffffff;
}

header #inner_header_post_thumb .dark_overlay .container .header-txt h3 {
  font-size: 24px;
  color: #ffffff;
  font-weight: 300;
}

header #inner_header_post_thumb .dark_overlay .container .header-txt p {
  font-size: 18px;
  font-weight: 300;
}

header #inner_header_post_thumb .dark_overlay .container .header-txt p strong {
  font-weight: 700;
}
<header>
  <div id="inner_header_post_thumb">
    <div class="dark_overlay">
      <div class="container">
        <div class="row header-txt">
          <div class="col-xs-12 col-sm-12">
            <h1>Title On Dark A Underlay</h1>
            <h3>Have a dark background image overlay without affecting other elements</h3>
            <p>No longer any need to re-save backgrounds as .png ... <strong>Awesome</strong></p>

          </div>
        </div>
      </div>
    </div>
  </div>
</header>

See a working codepen here

查看更多
Animai°情兽
3楼-- · 2019-01-11 06:46

Any child of an element with opacity set will take on that opacity.

To achieve this style you could use rgba colours and filters for IE for the background, and opacity on the textual elements. So long as the second box isn't a child of one of the text elements, then it won't inherit the opacity.

查看更多
登录 后发表回答