Smooth Fading Image Captions with Pure CSS3

Learn how to use CSS3 transitions to create nice, animated, semitransparent image captions. Full example and code download included.

Smooth Fading Image Captions with Pure CSS3

CSS3 promises to usher in a new wave of gorgeous web design, with lovely features such as drop shadows, text shadows, rounded corners, gradients, and border images.

One CSS3 feature that is really starting to gain traction now is transitions. CSS transitions allow you to smoothly animate an element's CSS properties from one state to another, without using a single line of JavaScript.

Most modern browsers now have good support for transitions, including Firefox 4, Safari 5, Mobile Safari and Opera 10. IE sadly doesn't (and this includes the upcoming IE9). Fortunately, transitions usually degrade gracefully in browsers that don't support them—instead of elements slowly moving from one state to another, they simply jump instantly between states.

In this tutorial I'll show you how to use CSS3 transitions to create a nice fading caption effect on images. View it in action — as you hover over an image with the mouse, you'll see its caption fade in. (Assuming you're not using IE, of course.)

Naturally, mobile browsers with touchscreens don't have a concept of hovering. Instead, you can tap an image to see its caption.

Along the way, we'll also use some new HTML5 elements like figure and figcaption to create nice semantic markup.

Ready? Let's get started!

Step 1. Create the basic markup

We'll start by creating our basic page markup:


<!doctype html>
<html lang="en">
<head>
<title>Smooth Fading Image Captions with Pure CSS3 | Demo | Elated.com</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
</head>
<body>

</body>
</html>

This is fairly standard stuff. We use the HTML5 doctype, create a head and body, and specify a title and character set.

Step 2. Add the article

Now we'll add the article which will contain our images. For this example, I used the preface from Aircraft and Submarines by Willis J. Abbot:


<article>

  <h1>Aircraft and Submarines</h1>
  <h2>The Story of the Invention, Development, and Present-Day Uses of War's Newest Weapons</h2>
  <h3>By Willis J. Abbot</h3>
  <h4>Preface</h4>

  <p>Not since gunpowder was first employed in warfare has so
  revolutionary a contribution to the science of slaughtering men been
  made as by the perfection of aircraft and submarines. The former
  have had their first employment in this world-wide war of the
  nations. The latter, though in the experimental stage as far back as
  the American Revolution, have in this bitter contest been for the
  first time brought to so practical a stage of development as to
  exert a really appreciable influence on the outcome of the struggle.</p>

  <p>Comparatively few people appreciate how the thought of navigating
  the air's dizziest heights and the sea's gloomiest depths has
  obsessed the minds of inventors. From the earliest days of history
  men have grappled with the problem, yet it is only within two
  hundred years for aircraft and one hundred for submarines that any
  really intelligent start has been made upon its solution. The men
  who really gave practical effect to the vague theories which others
  set up&mdash;in aircraft the Wrights, Santos-Dumont, and Count Zeppelin;
  in submarines Lake and Holland&mdash;are either still living, or have
  died so recently that their memory is still fresh in the minds of
  all.</p>

  <p>In this book the author has sketched swiftly the slow stages by
  which in each of these fields of activity success has been attained.
  He has collated from the immense (p. iv) mass of records of the
  activities of both submarines and aircraft enough interesting data
  to show the degree of perfection and practicability to which both
  have been brought. And he has outlined so far as possible from
  existing conditions the possibilities of future usefulness in fields
  other than those of war of these new devices.</p>

  <p>The most serious difficulty encountered in dealing with the present
  state and future development of aircraft is the rapidity with which
  that development proceeds. Before a Congressional Committee last
  January an official testified that grave delay in the manufacture of
  airplanes for the army had been caused by the fact that types
  adopted a scant three months before had become obsolete, because of
  experience on the European battlefields, and later inventions before
  the first machines could be completed. There may be exaggeration in
  the statement but it is largely true. Neither the machines nor the
  tactics employed at the beginning of the war were in use in its
  fourth year. The course of this evolution, with its reasons, are
  described in this volume.</p>

  <p>Opportunities for the peaceful use of airplanes are beginning to
  suggest themselves daily. After the main body of this book was in
  type the Postmaster-General of the United States called for bids for
  an aërial mail service between New York and Washington&mdash;an act urged
  upon the Government in this volume. That service contemplates a
  swift carriage of first-class mail at an enhanced price&mdash;the
  tentative schedule being three hours, and a postage fee of
  twenty-five cents an ounce. There can be no doubt of the success of
  the service, its value to the public, and its possibilities of
  revenue to the post-office. Once its usefulness is established it
  will be extended to routes of similar length, such as New York
  (p. v) and Boston, New York and Buffalo, or New York and
  Pittsburgh. The mind suggests no limit to the extension of aërial
  service, both postal and passenger, in the years of industrial
  activity that shall follow the war.</p>

  <p>In the preparation of this book the author has made use of many
  records of personal experiences of those who have dared the air's
  high altitudes and the sea's stilly depths. For permission to use
  certain of these he wishes to express his thanks to the Century Co.,
  for extracts from <i>My Airships</i> by Santos-Dumont; to Doubleday, Page
  &amp; Co., for extracts from <i>Flying for France</i>, by James R. McConnell;
  to Charles Scribner's Sons, for material drawn from <i>With the French
  Flying Corps</i>, by Carroll Dana Winslow; to <i>Collier's Weekly</i>, for
  certain extracts from interviews with Wilbur Wright; to <i>McClure's
  Magazine</i>, for the account of Mr. Ray Stannard Baker's trip in a
  Lake submarine; to Hearst's International Library, and to the
  <i>Scientific American</i>, for the use of several illustrations.</p>

  <footer>Source text via <a href="http://www.gutenberg.org/files/30047/30047-h/30047-h.htm">Project Gutenberg</a>.</footer>

</article>

I've used a couple of HTML5 elements in this markup: article to contain the article, and footer for the article's footer text. This adds structure to our article, and will also make it easier to style later on.

Step 3. Add the figures

Now we can add our images to the article. We'll insert these between the paragraphs of text (new markup shown in bold):


<article>

  <h1>Aircraft and Submarines</h1>
  <h2>The Story of the Invention, Development, and Present-Day Uses of War's Newest Weapons</h2>
  <h3>By Willis J. Abbot</h3>
  <h4>Preface</h4>

  <figure style="width: 300px; height: 373px; float: left; margin-right: 20px;">
    <img src="images/fighting-by-sea-and-sky.jpg" alt="Fighting by Sea and Sky" />
    <figcaption>
      <h3>Fighting by Sea and Sky.</h3>
      <p>Painting by John E. Whiting.</p>
    </figcaption>
  </figure>

  <p>Not since gunpowder was first employed in warfare has so
  revolutionary a contribution to the science of slaughtering men been
  made as by the perfection of aircraft and submarines. The former
  have had their first employment in this world-wide war of the
  nations. The latter, though in the experimental stage as far back as
  the American Revolution, have in this bitter contest been for the
  first time brought to so practical a stage of development as to
  exert a really appreciable influence on the outcome of the struggle.</p>

  <p>Comparatively few people appreciate how the thought of navigating
  the air's dizziest heights and the sea's gloomiest depths has
  obsessed the minds of inventors. From the earliest days of history
  men have grappled with the problem, yet it is only within two
  hundred years for aircraft and one hundred for submarines that any
  really intelligent start has been made upon its solution. The men
  who really gave practical effect to the vague theories which others
  set up&mdash;in aircraft the Wrights, Santos-Dumont, and Count Zeppelin;
  in submarines Lake and Holland&mdash;are either still living, or have
  died so recently that their memory is still fresh in the minds of
  all.</p>

  <p>In this book the author has sketched swiftly the slow stages by
  which in each of these fields of activity success has been attained.
  He has collated from the immense (p. iv) mass of records of the
  activities of both submarines and aircraft enough interesting data
  to show the degree of perfection and practicability to which both
  have been brought. And he has outlined so far as possible from
  existing conditions the possibilities of future usefulness in fields
  other than those of war of these new devices.</p>

  <figure style="width: 452px; height: 300px; float: right; margin-left: 20px;">
    <img src="images/a-battle-in-mid-air.jpg" alt="A Battle in Mid-air" />
    <figcaption>
      <h3>A Battle in Mid-air.</h3>
      <p>(Note rifleman on wing of airplane.)</p>
      <p>From the painting by Lieutenant Farré.</p>
    </figcaption>
  </figure>

  <p>The most serious difficulty encountered in dealing with the present
  state and future development of aircraft is the rapidity with which
  that development proceeds. Before a Congressional Committee last
  January an official testified that grave delay in the manufacture of
  airplanes for the army had been caused by the fact that types
  adopted a scant three months before had become obsolete, because of
  experience on the European battlefields, and later inventions before
  the first machines could be completed. There may be exaggeration in
  the statement but it is largely true. Neither the machines nor the
  tactics employed at the beginning of the war were in use in its
  fourth year. The course of this evolution, with its reasons, are
  described in this volume.</p>

  <p>Opportunities for the peaceful use of airplanes are beginning to
  suggest themselves daily. After the main body of this book was in
  type the Postmaster-General of the United States called for bids for
  an aërial mail service between New York and Washington&mdash;an act urged
  upon the Government in this volume. That service contemplates a
  swift carriage of first-class mail at an enhanced price&mdash;the
  tentative schedule being three hours, and a postage fee of
  twenty-five cents an ounce. There can be no doubt of the success of
  the service, its value to the public, and its possibilities of
  revenue to the post-office. Once its usefulness is established it
  will be extended to routes of similar length, such as New York
  (p. v) and Boston, New York and Buffalo, or New York and
  Pittsburgh. The mind suggests no limit to the extension of aërial
  service, both postal and passenger, in the years of industrial
  activity that shall follow the war.</p>

  <figure style="width: 420px; height: 321px; float: left; margin-right: 20px;">
    <img src="images/the-giant-and-the-pigmies.jpg" alt="The Giant and the Pigmies" />
    <figcaption>
      <h3>The Giant and the Pigmies.</h3>
      <p>Painting by John E. Whiting.</p>
    </figcaption>
  </figure>

  <p>In the preparation of this book the author has made use of many
  records of personal experiences of those who have dared the air's
  high altitudes and the sea's stilly depths. For permission to use
  certain of these he wishes to express his thanks to the Century Co.,
  for extracts from <i>My Airships</i> by Santos-Dumont; to Doubleday, Page
  &amp; Co., for extracts from <i>Flying for France</i>, by James R. McConnell;
  to Charles Scribner's Sons, for material drawn from <i>With the French
  Flying Corps</i>, by Carroll Dana Winslow; to <i>Collier's Weekly</i>, for
  certain extracts from interviews with Wilbur Wright; to <i>McClure's
  Magazine</i>, for the account of Mr. Ray Stannard Baker's trip in a
  Lake submarine; to Hearst's International Library, and to the
  <i>Scientific American</i>, for the use of several illustrations.</p>

  <footer>Source text via <a href="http://www.gutenberg.org/files/30047/30047-h/30047-h.htm">Project Gutenberg</a>.</footer>

</article>

For the figures, we use 2 more HTML5 elements: figure and figcaption. This allows us to associate an image with a caption by wrapping both the img and figcaption elements inside a parent figure element. Nice!

Notice that we've specified the image widths and heights on the figure elements, not the img elements. This ensures that each figure has the correct width and height, which is important when it comes to styling our caption overlays later.

Step 4. Style the article

Styling the article

We're now ready to add our CSS. First we'll style the page body and article:


<style type="text/css">

/* Add some margin to the page and set a default font and colour */

body {
  margin: 30px;
  font-family: "Georgia", serif;
  line-height: 1.8em;
  color: #333;
}

/* Set the article dimensions */

article {
  width: 800px;
  padding: 50px;
  margin: 0 auto;
  display: block;
  font-size: 1.2em;
}

article h2 {
  line-height: 1.5em;
}

/* Style the article footer */

footer {
  font-style: italic;
  font-size: .9em;
}

First we've given the body some margin, and specified default fonts and colours. We then style the article element, giving it a fixed width and some padding, and centring it in the page with margin: 0 auto. We also use display: block to tell browsers that aren't aware of the article element to display it as a block-level element (otherwise it'll default to inline).

We also add some line spacing to the h2 heading in the page, and style the footer element in a small italic font.

Step 5. Style the figures

Next we style the figure elements, which hold the images and image captions:


/* Style the figures */

figure {
  position: relative;
  display: block;
  border: 1px solid #333;
  margin: 5px 0 10px 0;
}

Since we'll be using absolutely-positioned elements within the figures, we set position: relative on the figures to ensure that the absolutely-positioned elements are relative to the figures, rather than to the page. As with the article element, we specify display: block to ensure that the figures display as block-level elements in older browsers.

Step 6. Style the figure captions

Styling the captions

Now comes the fun bit! A figure's caption needs to sit on top of its image, positioned at the bottom of the image, and it needs to have a translucent background that stretches across the entire width of the image. It also needs to be hidden initially, so that it can fade in when the mouse moves over the figure. Here's how we do it:


/* Style the figure captions, hiding them by default */

figcaption {
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
  font-size: .7em;
  color: #fff;
  background-color: rgba(0,0,0,.7);
  opacity: 0;
  -webkit-transition: opacity .5s ease-in-out;
  -moz-transition: opacity .5s ease-in-out;
  -o-transition: opacity .5s ease-in-out;
  transition: opacity .5s ease-in-out;
}

Let's break this CSS down:

  1. Position the caption
    We absolutely position the caption at the bottom left of its containing figure element.
  2. Set width, font size and colour
    A 100% width ensures that the caption stretches across the width of the figure element. We also give the caption small white text.
  3. Set a translucent background and hide the caption
    We use the rgba() colour format to specify a black background with 70% opacity. We then set the overall opacity of the caption to zero, thereby hiding the caption.
  4. Set up the transition effect
    Now we come to the meat of the tutorial — the transition effect. transition: opacity .5s ease-in-out tells the browser to smoothly animate the opacity property of this element over a period of half a second, and to ease the animation in and out — in other words, change the opacity more slowly towards the start and end of the animation. As well as the standard transition property, we also set vendor-specific versions of the property for WebKit, Gecko and Opera browsers.

We've set up our transition, but in order to actually make it happen we need to add a :hover pseudo-class to the figure elements that sets the caption's opacity to 100% when the mouse moves over it:


/* Display the captions on hover */

figure:hover figcaption {
  opacity: 1;
}

Now, when the mouse moves over a figure element, its figcaption element changes opacity from 0 to 1. Thanks to the transition we set up earlier, this change happens smoothly over a period of half a second. Similarly, when the mouse leaves the figure, the figcaption's opacity gradually transitions from 1 back to 0, thereby hiding the caption again.

We'll make some final tweaks to the captions, adding some margin and padding to a caption's content, with extra padding on the top and bottom elements to space everything out nicely. Let's also give the captions (and headings) their own font:


/* Add padding and margin to the caption contents */

figcaption * {
  padding: 0 10px;
  margin: 0;
}

figcaption *:first-child {
  padding-top: 5px;
}
figcaption *:last-child {
  padding-bottom: 5px;
}

/* Give captions and headings their own font */

figcaption, h1, h2, h3, h4 {
  font-family: "Lucida Sans Unicode", "Lucida Grande", sans-serif;
}

Step 7. Add IE support

IE menu option

We're pretty much done now. However, as mentioned at the start of the article, IE doesn't support transitions. For that matter, IE8 and earlier don't even support opacity or the rgba() colour format!

While there's not much we can do about transitions (apart from resort to JavaScript), we can use some IE-specific CSS to at least make the captions appear when the images are hovered over, and also to give the captions a semitransparent background:


figcaption {
  filter: alpha(opacity=0);
}

figure:hover figcaption {
  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#aa000000,endColorstr=#aa000000);
}

The first rule uses IE's filter property to set the captions' opacity to zero, while the second rule effectively creates a background gradient where the start and end colours are the same. Doing this lets us specify an alpha transparency value for the background (#aa in this case). We don't need to set the caption's opacity to 100%, since this happens automatically when the semitransparent background is set.

Here's a good breakdown of the different ways you can create semitransparent backgrounds in IE and other browsers.

We still have more work to do for IE, though. IE8 and earlier don't recognise HTML5 elements such as article, figure and figcaption. This shouldn't be a problem, except that IE won't let you style an element it doesn't recognise!

Fortunately, the fix is simple — just create the required elements using JavaScript's document.createElement() method. We'll put this code in conditional comments so that only IE8 and earlier see it:


<!--
  Add support for HTML5 elements in IE <= 8
-->

<!--[if lt IE 9]>
<script type="text/javascript">
document.createElement('article');
document.createElement('figure');
document.createElement('figcaption');
</script>
<![endif]-->

Now our captions function correctly in Internet Explorer. They don't fade, but at least they work!

If anyone's interested in a JavaScript solution to make the captions fade in IE, let me know in the comments below, and I'll write a followup tutorial!

I should also point out that the captions won't work in IE6 at all, since IE6 doesn't support :hover on anything but links. C'est la vIE. :)

Summary

In this tutorial you've learned how to create a nice fading caption effect on images in your webpages. Along the way, you've explored CSS3 transitions, looked at some new HTML5 elements, and learned some tricks for dealing with translucent backgrounds and HTML5 elements in Internet Explorer.

If you want more info about how CSS3 transitions work, check out the CSS Transitions spec over at the W3C.

I hope you enjoyed reading, and as always, I'd love to hear your feedback in the comments below. Happy coding!

Follow Elated

Related articles

Responses to this article

2 responses (oldest first):

ps
26-Dec-11 13:06
This is cool, thanks! I have stretched the effect over the whole image, but now it is not "clickable". Is there a way to change this?
08-Jan-12 03:07
@ps: Please post your question, along with the URL of the page with the problem, in a new topic:

http://www.elated.com/forums/authoring-and-programming/topic/new/

Post a response

Want to add a comment, or ask a question about this article? Post a response.

To post responses you need to be a member. Not a member yet? Signing up is free, easy and only takes a minute. Sign up now.

Top of Page