jgozal jgozal - 2 months ago 8
CSS Question

How to create black transparent overlay/ modal dialog with centered text on an image

I would like to create a black transparent overlay with centered text on an image on hover. Sort of how Instagram does it hear with each image here (hover over the images)

I have tried doing something like this:

HTML:

<div class="parent">
<img src="someimageurl">
<div class="child">
<p>some text</p>
</div>
</div>


CSS:

.parent {
position: relative;
background: black;
}
.child {
position: absolute;
top: 50%;
left: 50%;
margin-right: -50%;
transform: translate(-50%, -50%);
visibility: hidden;
}
.child p {
text-align: center;
color: white;
font-size: 1.2em;
}
.child:hover {
visibility: visible;
opacity: 4;
}


This has failed miserably. Please note that the solution should also work with video tags.

Answer

Try the following:

  1. Give your container a relative position.
  2. Assign display: flex; justify-content: center; align-items: center; and position: absolute; to your modal.
  3. Hide the overlay using background-color: rgba(0, 0, 0, 0); and reveal it on hover with background-color: rgba(0, 0, 0, 0.5);. (Using rgba() will not assign the opacity to your text, which is why you should use it over opacity) To hide the text, you can use visibility: hidden; and visibility: visible; to show it.

.container {
  width: 300px;
  height: 300px;
  position: relative;
  font-family: Helvetica,sans-serif;
}

img {
  background-color: red;
  width: 300px;
  height: 300px;
}

.overlay {
  display: flex;
  justify-content: center;
  align-items: center;
  color: red;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  top: 0;
  background-color: rgba(0, 0, 0, 0);
  visibility: hidden;
}

.container:hover > .overlay {
  background-color: rgba(0, 0, 0, 0.5);
  visibility: visible;
}
<div class="container">
  <img src="http://i.stack.imgur.com/Zw1MI.jpg"/>
  <div class="overlay">Darth Maul</div>
</div>

Comments