CSS-Tricks PSD to HTML

Give Your Images Space and Captions For Better Layout

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.

caption2.png

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>
</div>

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.

caption1.png

[LIVE EXAMPLE]

[DOWNLOAD EXAMPLE]


Theoretically Related Articles:

Discussion Elsewhere


Responses


  1. 1

    Gravatar

    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.


    Comment by LadynRed — August 15, 2007 @ 6:30 am

  2. 2

    Gravatar

    @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:
    http://www.positioniseverything.net/explorer/doubled-margin.html

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


    Comment by chriscoyier — August 15, 2007 @ 8:05 am


Leave a comment

Sick of typing in all this info everytime you comment? Register or Login and save yourself time!

Live Comment Preview


Thank you for visiting CSS-Tricks! I'm glad you found an article useful enough to print out! Remember to visit css-tricks.com often for more fresh content.