I’ve been in this situation quite often: We have a list of elements that need to be laid out on the page in the following manner:
- Each element has fixed width / height.
- There are a number of elements in a row.
- There must be an equal space between any two elements.
Well, this is a classic case for a table! Yes! I can see it happening; with the right cellspacing and background color, it will be perfect.
So, CSS. The requirements are:
- Each item is 50x50 pixels.
- 15 pixels between items.
- 4 items in a row.
We?ll create a
- to contain all the items. Its width will be 245 pixels, to house 4 items and 3 spaces between them (450 + 315).
To create a list of items in a row we shall use float: left (or right) in order to place the elements on a particular side. Every time an item reaches the edge of the box in which it is contained, it will drop down to the next row.
To create the spaces between the items, we?ll use margin-right. And here is the catch:
- ’s as you want, without harming the layout.
As you can see, the spacing is created for each item.
Due to a lack of spacing on the right, the last block of each row drops down. Because of the bottom margins, there is superfluous space at the bottom of the container. Our design has gone wrong.
How about if we don?t want the last column to have a side margin and the last row a bottom margin?
The sophistication of CSS3 (nth-child) is yet to be here.
We keep the margins.
We?ll enlarge the container
- to 260 pixels, so that it contains the right margin of the last box.
We create another wrapper div, hide the overflow and give it a width of 245 pixels, and inside we place the
- with our items. The
- with the items will actually flow on, but because we?ve ?trimmed? it the new wrapper div, we won?t see the superfluous space on the side.
And what about the space at the bottom? We?ll give the
- containing the items a negative margin-bottom as large as the items’ lower margin.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
This example can contain as many