简体   繁体   中英

An overlay over an image using css

I am trying to put a layer at the top of an image using css. But for some reason the img class is not taking the effect.

Html --

<div class="slider">
  <img src="http://kenwheeler.github.io/slick/img/fonz1.png" />
</div>

Demo -- https://jsfiddle.net/squidraj/b49a6xkd/

Any help is highly appreciated.

You're applying the background color to the img element, so that background will appear behind the img element. Use a pseudo element to overlay the image instead, and apply the background color to the pseudo element.

 .slider { margin: 0 auto; text-align: center; } .slider .wrap { position: relative; display: inline-block; } .slider .wrap:after { background: rgba(255, 255, 255, 0.5); content: ''; position: absolute; top: 0; left: 0; right: 0; bottom: 0; } 
 <div class="slider"> <div class="wrap"> <img src="http://kenwheeler.github.io/slick/img/fonz1.png"> </div> </div> 

This can be accomplished by using psuedo elements . You're essentially adding a container to the page, and setting the background-color of that .

The fiddle .

The CSS

.slider:before {
  content:'';
  position:absolute;
  display:block;
  width:100%;;
  height:400px;
  background-color:rgba(255,255,255,.5);
  z-index:1;
}

I provided a jsfiddle for you: https://jsfiddle.net/anp8wgqt/

As mentioned, you need to put some element above the image for the overlay to show. I've done here using a pseudo element, so the same markup as you already have.

 .slider { position: relative; width: 100%; margin: 0 auto; } .slider img { width: 100%; height: auto; display: block; } .slider::after{ content: ''; position: absolute; z-index: 1; left: 0; top: 0; width: 100%; height: 100%; background: rgba(255, 255, 255, 0.5); opacity: 0; transition: opacity 350ms; } .slider:hover::after { opacity: 1; } 
 <div class="slider"> <img src="http://kenwheeler.github.io/slick/img/fonz1.png" /> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM