Display <div> or <span> over image on :hover in HTML

JavascriptWeb DevelopmentFront End Scripts

In order to allow div or span element to appear over an image when mouse hover over the image, this can be done with the help of .image:hover overlay,

To position .overlay element absolutely relative to the parent element we give height and width to 100% for all image sizes making parent element inline-block

HTML

<div class="image">
   <img src="..." />
   <div class="overlay">Content to be displayed on hover</div>
</div>

CSS

By hiding the .overlay element by default, we use the selector .image:hover .overlay to change the styling on hover. Due to the HTML structure, this works well because .overlay is a descendant element.
.image {
   position:relative;
   display:inline-block;
}
.overlay {
   display:none;
}
.image:hover .overlay {
   width:100%;
   height:100%;
   background:rgba(0,0,0,.5);
   position:absolute;
   top:0;
   left:0;
   display:inline-block;
   -webkit-box-sizing:border-box;
   -moz-box-sizing:border-box;
   box-sizing:border-box;

   /* All other styling - see example */
   img {
      vertical-align:top;
   }
}
raja
Published on 11-Apr-2018 13:30:44
Advertisements