Alt-Web Design & Publishing
CSS Floats and Margins Demo:
3 Evenly-Spaced Boxes
Description:
This CSS tutorial demonstrates how floats and margins can be used to create 3 evenly-spaced, horizontal boxes. Tested and works in FF2+, IE6+, Opera 9, Safari 3+ and Chrome.
Example:
Container Division width = 900 px.
Box #1
Float: left
border: 4px
width: 250px
Box #2
Float: left
border: 4px
width: 250px;
margin-left: 63px;
No need to define a margin-right value because it is implied.
Box #3
Float: right;
border: 4px
width: 250px;
Some text below the cleared floats.
Method:
Begin with a container division that is larger than the combined width and borders or your 3 boxes. For this demo, container width (900px) minus combined width of boxes (250px x 3 = 750px) and left & right borders (4px x 6 = 24) = total margins between boxes (126px). Total margins (126) divided by # of margins needed (2) = 63px for margins between boxes. If we've done our math correctly, content inside the #Container division will fit like a glove. If our math is off, we may notice a few problems.
IMPORTANT: Internet Explorer requires that the #Container width be equal or greater than the width of content inside it or you will get a phenomenon known as Float Drop. Float Drop can also occur when an oversized image or non-breaking text element such as a long URL is placed inside one of the floated #Boxes. As a precaution, we've added Overflow and Word-Wrap CSS properties to each of our 3 #Boxes.
CSS Code
/**zero out default browser settings**/
* {margin:0; border: 0; padding: 0; font-size: 100%;}
#Container {
font-family: Verdana, Arial, Helvetica, sans-serif;
border: 1px solid red;
width: 900px;
height: auto;
margin:0 auto; /**centered**/}
#Container p {
line-height:1.4;
padding: 0 20px 0 20px;
font-size:12px;}
#Box1, #Box2, #Box3 {
width: 250px;
min-height: 150px; /**non-IE browsers**/
_height: 150px; /**IE6 only**/
margin-bottom:45px;
border: 4px solid gold;
background:#C2DAD7;
/**to reduce float drop issues in IE6**/
overflow: hidden;
word-wrap: break-word;}
#Box1 h2,#Box2 h2,#Box3 h2 {
padding:10px 20px 9px 0;
text-align: right;
font-size: 14px;}
#Box1 {float: left;}
#Box2 {margin-left: 63px; float: left;}
#Box3 {float: right;}
.clear {clear: both; line-height: 1px; visibility: hidden}
HTML Code
<div id="Container">
<div id="Box1">
<h2>Box #1 </h2>
<p>Your text goes here</p>
</div> <!--end Box1 -->
<div id="Box2">
<h2>Box #2</h2>
<p>Your text goes here</p>
</div> <!--end Box2 -->
<div id="Box3">
<h2>Box #3</h2>
<p>Your text goes here</p>
</div> <!--end Box3 -->
<!--clear floats with a <br> <p> or <hr>-->
<hr class="clear" />
</div> <!--end Container -->
