CSS No-Float Positioning Of Text Next To Image

Posted in: Computers - CSS Tutorials

Note: This article was written for users with more recent browsers - IE8+, Firefox 3.5, and Safari 4. The examples may not display correctly in older browsers.

You may often find yourself in a situation where a certain design is not conducive to using CSS floats. Take for example the following HTML and CSS:

<div>
    <img src="/image.jpg" alt="alternate text">
    <p>Text I want next to the image.</p>
</div>

div {
    background-color: #aaa;
    border: 1px solid black;
    width: 300px;
    padding: 25px;
}
img {
    width: 100px;
    margin: 0 25px 0 0;
    float: left;
}
p {
    margin: 0;
}

Which would look like this...

Example Image

Text I want next to image will go here.

If you are using a modern web browser, you will see the colored div does not expand to surround the image. If you're using IE7 or IE6, it will probably look alright. How do we get around this problem? We can't manually set the height of the div because we don't know exactly how tall the image is. So instead of floating the image, let's set the image and the text as inline-blocks, which will position the elements side by side.

div {
    background-color: #aaa;
    border: 1px solid black;
    width: 300px;
    padding: 25px;
}
img {
    width: 100px;
    margin: 0 25px 0 0;
    display: inline-block;
}
p {
    width: 125px;
    display: inline-block;
}

Which looks like this...

Example Image

Text I want next to image.

If you're using a modern browser, you will see that the text doesn't line up with the top of the image. The solution? Set the vertical-align property of the paragraph.

p {
    width: 125px;
    display: inline-block;
    vertical-align: top;
}

The vertical-align: top tells the paragraph to align with the tallest element next to it.

Example Image

Text I want next to image.

In order to make this work for IE6 and IE7, you will need to implement a browser specific style sheet or use IE6+7 CSS hacks. The root problem is that IE6+7 doesn't support inline-blocks. The final cross browser solution will look like this:

div {
    background-color: #aaa;
    border: 1px solid black;
    width: 300px;
    padding: 25px;
}
img {
    width: 100px;
    margin: 0 25px 0 0;
    display: inline-block;
}
*img {
    display: inline;
}
p {
    width: 125px;
    display: inline-block;
    vertical-align: top;
}
*p {
    display: inline;
}

Which looks like this in all browsers:

Example Image

Text I want next to image.