CSS Layout using percentage (%) and pixels (px) together
Quite often either I or other people are asked how to control CSS layouts using both pixels and percentages. The answer is a simple one but I will demonstrate the code needed a little more so you can better understand it. For this tutorial I will be basing the tutorial on a post I answered on Neowin.net (A forum I frequent).
Ok, so start with we want to have a main div which stretches for 80% of the browser width. Our main div will have the class .red and uses the following CSS.
.red {
background-color: #F00;
width: 80%;
height: 800px; /* Just for illustration purposes */
margin-right: auto;
margin-left: auto;
}
So you can see that our .red class has an 80% width and uses margin auto for left and right. This centers the div within the browser and gives it a percentage of 80%.
Now, what we want to achieve is the following. A left column within .red with the width of 250px and a right column that will fill the remainder of the 80% width. Tricky? Not really…
Our left column will be called .blue and uses the following CSS.
.blue {
float: left;
width: 250px;
background-color: #06C;
color: #FFF;
font-family: Verdana, Geneva, sans-serif;
font-size: 12px;
text-align: center;
}
The CSS for our left column is simple as you can see. It uses 250px for the width and I simply float it to the left. Our right column however needs a little more to achieve our result and is achieved like so.
Our right column will have the class .green and uses the following CSS.
.green {
float: none;
left: auto;
margin-left: 250px;
position: static;
width: auto;
background-color: #0F6;
font-family: Verdana, Geneva, sans-serif;
font-size: 12px;
color: #000;
text-align: center;
}
.green has a static position, uses no float and has the width set to auto to ensure it fills the remaining space and the all important margin. the margin is the important part here as you need to set the value as per the width of your left column so if you have a column on the left that is 190px wide then your margin-left must be 190px and so on.
That is all you need for the desired effect (Live Demo). As usual, to leave me a fat comment dripping with greasy left over meat just look below.
Tags: CSS, design, Fat, Grease, Website, website design, XHTML

