Text and background-color overlay on image

14,168

Solution 1

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.

Solution 2

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);

}
Share:
14,168

Related videos on Youtube

ericsoco
Author by

ericsoco

once an architect, reborn as a coder/artist/interaction designer. now developing exhibits for san francisco's exploratorium. and still learning.

Updated on June 04, 2022

Comments

  • ericsoco
    ericsoco almost 2 years

    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>
    
  • ericsoco
    ericsoco almost 11 years
    you're both right -- forgot to set parent element's position. duh.