Obvious In Hindsight
Archive of tips, tricks and solutions for designers and programmers!

CSS: Horizontal row of images in a div


Often, images are arranged horizontally for the purposes of a navigation menu using images rather than standard text link. What in theory should be a relativly simple task can in practice become a nightmare if you overthink the process, are unaware of the idiosyncracities of the various popular browsers and the relevant workarounds. The simple fact of the matter is you can do this without any CSS whatsoever.

The correct way of arranging images inside a div

Let’s say we have six images that we want to arrange in our div. The following HTML code will do just that:

<div>

<img src=”images/image1.png”><img src=”images/image2.png”><img src=”images/image3.png”>img src=”images/image4.png”><img src=”images/image5.png”><img src=”images/image6.png”>

</div>

It’s very important to note that there can not be a space or spaces between your image elements. If you do, most browsers will render an undesirable blank space between your images of about five to ten pixels in width. It took me a few hours of searching to find this solution. The following code, which has spaces between the image elements is an example of the incorrect way of going about this.

What will not work

<div>

<img src=”images/image1.png”>

<img src=”images/image2.png”>

<img src=”images/image3.png”>

<img src=”images/image4.png”>

<img src=”images/image5.png”>

<img src=”images/image6.png”>

</div>

Why not use a horizontal unordered list?

You don’t need to unless your images are actually part of a list. You can, if you really feel the need but why add extraneous code?

Why not use CSS?

Again, you can but you don’t need to for the specific purpose of arranging the images. The most common way of going about this in CSS would involve styling an unordered list horizontally, the use of floats and various checks for cross-browser rendering. Furthermore, IE6 present various bugs with floats for novices. If you can do the exact same thing without CSS and with code then why bother?

Conclusion

Make sure there are no spaces between your image elements. Sure, the HTML markup will look cluttered but it’s the only workaround I’m aware of.

Everything’s obvious in hindsight, eh?

About these ads

No Responses to “CSS: Horizontal row of images in a div”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: