Search code examples
cssimageoverlaycaptionliquid-layout

How to make a liquid, centered, image with a caption overlay?


I'm trying with CSS to display an image centered with a caption overlay, and a liquid capability when the browser window is too small (shrink to fit).

My current best attempt looks like the following HTML (using Google's logo as sample image)

<div align="center">
   <div class="container">
      <img src="http://www.google.fr/images/logos/ps_logo2.png" class="picture" />
      <h3 class="caption">Image Caption</h3>
   </div>
</div>

with the following CSS

.container {
   position : relative;
   max-width : 364px;
}
.picture {
    border-radius:0.5em;
    box-shadow: 0px 0px 0.5em #000000;
    max-width:364px;
}
.caption {
    position:absolute;
    padding:0.25em;
    top:1em; left:0; right:0;
    color:black;
    background-color:rgba(0,0,0,0.2);
    text-align:center;
}

However, if it behaves centered as I want it to be for large browser windows, it doesn't shrink for small browser windows... Also I don't need IE support, a WebKit-specific (iPhone/Android) would be enough, and I would like to avoid JavaScript if possible.

JSFiddle ready-to play with version http://jsfiddle.net/kWH3C/1/


Solution

  • Just set the max-width to the container instead of the image and tell the image to be width:100%

    http://jsfiddle.net/Madmartigan/kWH3C/5/

    <div class="container">
        <img src="http://www.google.fr/images/logos/ps_logo2.png" class="picture" />
        <h3 class="caption">Image Caption</h3>
    </div>
    
    .container {
        position : relative;
        max-width : 364px;
        margin:0 auto;
    }
    .picture {
        border-radius:0.5em;
        box-shadow: 0px 0px 0.5em #000000;
        width:100%;
    }
    .caption {
        position:absolute;
        padding:0.25em;
        top:1em; left:0; right:0;
        color:black;
        background-color:rgba(0,0,0,0.2);
        text-align:center;
    }
    

    You don't need the outer div, and align="center" is deprecated in HTML5, use CSS for alignment and positioning.