Monday, April 6th, 2009
Simple overlay Image captions - CSS

Simple CSS captions overlay

Here’s a CSS only way to add an overlay caption on top of an image. There are of course javascript alternatives that require less HTML markup. These use the “title” tag as the caption. This post is simply an alternative for those who don’t want to mess around with javascript.

The transparency may not work in IE 6.

First the structure:

<div class="ImgCaptMain">
     <img border="0" alt="Some Image" src="images/current_chadcarr.jpg"/><br />
     <div class="ImgCaptDescBox">
         <div class="ImgCaptDescBg">
               <div class="ImgCaptDesc">
           	New York - Late 2008.
               </div>
         </div>
    </div></div>

Create a tree of 4 <div> tags. (<div> inside of a <div> inside of a <div> inside of a <div>)

  1. The first <div> doesn’t really have to do much other than give itself a position of relative.
  2. Then you place your <img> tag.
  3. The second <div> tag will contain the caption description and the transparent background

Here is the CSS:

.ImgCaptMain{
	/* only need a width if it's not inheriting one
 	width:; */
	position:relative;
}

.ImgCaptDescBox{
	position:absolute;
	bottom:0;
	left:0;
	/* since it's positioned absolutely it will need a width, but not height,
       that would fill the entire box covering the image */
	width:100%;
}

.ImgCaptDescBg{
	background:#333333;
	filter:alpha(opacity=50);
	-moz-opacity:0.5;
	-khtml-opacity: 0.5;
	opacity: 0.5;
}

.ImgCaptDesc{
	padding:5px;
	color:#fff;
	font-weight:normal;
	font-size:.785em;
	text-align:left;
}

The code above set’s the caption at the bottom as in figures A and B above. If you want the caption at the top of your image as in figures C and D, just change 1 simple piece of CSS. In the ImgCaptDescBox class, change bottom:0; to top:0; like below:

.ImgCaptDescBox{
	position:absolute;
	bottom:0;
	top:0;
	left:0;
	width:100%;
}

That’s it.

Here’s a working example:

sample css caption overlay

New York - Late 2008.

You could also add the “float:” property to the “ImgCaptMain” <div> if you want to align the image with text or other elements.

If you like it, share it:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • TwitThis

One Response to “Simple overlay Image captions - CSS”

  1. Ilan says:

    I just added a width:100%; to the ImgCaptDescBg class and the transparency is working on IE 6

    .ImgCaptDescBg{
    background:#333333;
    filter:alpha(opacity=50);
    -moz-opacity:0.5;
    -khtml-opacity: 0.5;
    opacity: 0.5;
    width:100%;
    }

    Thanks for all your articles
    Ilan

Leave a Reply