In this post I want to reply to a frequently asked question that I receive from my readers about how to distribute horizontally a certain number of elements within a main container using CSS. This problem is not particularly complex and can be solved simply using the CSS selector
:first-child
.Before to proceed I suggest you to download my CSS 2 Visual Cheat Sheet for a practical reference guide to CSS 2 properties that can help you understand concepts illustrated in this post. The picture below illustrates an example of horizontal distribution:
This is the HTML code you can use to define the structure of your document:
In order to distribute horizontally the three elements contained into the wrapper we have to use some lines of CSS code. At first sight, a practical solution could be to define a class (
.section
), with the properties width
andmargin-right
set to a specific value, and apply it to each
element contained into the wrapper. The problem is the right margin of the last
element that exceeds the width of the wrapper:
This is a problem because web browsers render the page in this way:
The last
layer is moved below. The question is: How can you remove the external margin of the last element without using a different CSS class with the property
margin-right
sets to 0?Solution
As I said at the beginning of this article, the simplest solution is to use the CSS selector
:first-child
and invert the position of the margin from right to left. :first-child
allow you to get an element that is the first child of another element. In this way the selector allows you to remove the left margin easily.The first step is to define the wrapper using the following CSS code:
#wrapper{
width:320px;
height:60px;
background:#EFEFEF;
}
The following code define the class
.section
to apply to each element within the main wrapper..section{
border:solid 1px #999;
float:left;
height:58px;
margin-left:10px;
width:98px;
}
In this example I used fixed values for the properties
width
and margin-left
but you can also use relative value (percentage). Now we have to remove the left margin adding the following code:#wrapper div:first-child{margin-left:0px;}
Browsers interpret the previous line in this way: get the first
element contained into the element with
ID=wrapper
and set the property margin-left
to 0. And this is the result:The only advice is the following: IE 6 doesn’t support the selector
:first-child
. You can use conditional comments to define a specific CSS file for IE6 and add a new class (for example .section-first
) with the same properties of the class .section
but the property margin-left
sets to 0.
Aucun commentaire:
Publier un commentaire