Grow your CSS skills. Land your dream job.

Give Your Images Space and Captions For Better Layout

Published by Chris Coyier

You can always float your images to one side or the other and give them a bit of a margin just by giving them a class like "floatright" and declaring that class as:

.floatright {
float: right;
margin: 5px;

That's fine and dandy, but let's switch things up a bit in order to give us more control as well as add captions to the images. This adds a nice touch to any web article and a more professional layout feel.


Instead of giving the image a class, put it inside of a div and give the div a class. Inside the div, include the image as well as the caption:

<div class="rightside_image">
  <img src="egg.jpg" alt="egg" />
  <p>Stop-motion image of an<br />egg getting sliced in half.</p>

Then declare that class in your CSS:

div.rightside_image {
float: right;
padding: 10px;
margin: 10px;
border: 2px solid #cccccc;
text-align: center;
font-size: 0.8em;
font-style: italic;

You could then copy and change this declaration to create different variations, such as a left floated image, centered images, different background colors, etc.





  1. LadynRed
    Permalink to comment#

    Good method, but be aware that IE is going to bugger it up with it’s doubled-float margin bug, which happens when you float an element in 1 direction and then apply a margin in the same direction, ie. float: right with a right margin. In your example, IE will make the right margin 20px instead of 10px and could cause float drop and other layout problems in a tight layout.

    The fix is to add display: inline to the floated element and then target only IE 6 with conditional comments and a separate ‘fixes’ css file.

  2. @LadynRed: Great point! People should be aware of this ridiculous bug. Fortunately, the fix is easy and simple.

    People can check out this article for more information:

    I’ll try to remember to point this out in a future post.

  3. Jingwen
    Permalink to comment#

    its good layout

This comment thread is closed. If you have important information to share, you can always contact me.

*May or may not contain any actual "CSS" or "Tricks".