Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Text and background-color overlay on image

I'm trying to create a solid-color overlay that exactly matches the size of an image, and display text on that overlay. I'd like to do this with HTML and CSS only, if possible.

image without overlay

image with overlay and text

The image may be of any size, and will be sized to fit and centered within its parent container. Something like this (which does not work):

HTML:

<div class="img-overlay">
  <img src="file.jpg">
  <div class="overlay">Text will flow...</div>
</div>

CSS:

.img-overlay img {
  margin: 0 auto;
  max-height: 100%;
}
.overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%
  background-color: rgba(255,255,255,0.5);
}

I thought that HTML5's <figure> tag might help here, but haven't had much success on that front. The following keeps the caption width pegged to the image width, but when I try to remove it from the document flow and position it over the image, it ends up to the left of the image due to the image centering via margin: 0 auto;.

<figure>
  <img src="file.jpg">
  <figcaption>Text will flow...</figcaption>
</figure>
like image 476
ericsoco Avatar asked Aug 11 '13 18:08

ericsoco


2 Answers

I made an example for you. http://jsfiddle.net/kb3Kf/2/

The main thing that was missing was that you gave the text an Absolute position but didn't give the wrapper a Relative one, like so:

.img-overlay
{
    position: relative;
}

It's really simple, you can take it to many directions. Tell me if that's what you wanted.

like image 190
Itay Avatar answered Sep 18 '22 06:09

Itay


You are just missing setting the position of the parent img-overlay element. When something has a position of "absolute", that refers to where it is in relation to its parent. The parent needs to have positioning.

.img-overlay {
    position: relative;
    width: 300px;

}

.img-overlay img {
width:100%;
}

.overlay {
  position: absolute;
  width:100%;
  height: 100%;
  top:0px;
  left:0px;
  background-color: rgba(255,255,255,0.5);

}
like image 21
helixmat Avatar answered Sep 22 '22 06:09

helixmat