I have this problem. I have a containing div with width set to 100%. Inside this div I have four other divs which I want to align centered besides each other. All of the divs has the same width set to 20%. I use float:left; on the four boxes to make them appear besides each other but I cannot get them centered inside the containing div. Is there any way to do this? Here's how I want the boxes to appear: Thanks in advance!
If you want gaps between the boxes, I think you would need to put in dummy div's as spacers. <body> <div style="margin:0 auto;text-align:center;"> <div style="border:1px solid #000;margin:auto 25%;"> <div style="width:25%;float:left;background-color:orange;margin:0 auto 0 auto">s</div> <div style="width:25%;float:left;background-color:red;margin:0 auto 0 auto">s</div> <div style="width:25%;float:left;background-color:green;margin:0 auto 0 auto">s</div> <div style="width:25%;float:left;background-color:blue;margin:0 auto 0 auto">s</div> <div style="clear:both;"></div> </div> </div> </body> Code (markup):
Thanks for the fast reply! I added spacers between the divs like this: <body> <div style="margin:0 auto;text-align:center;width:100%;"> <div style="border:1px solid #000;margin:auto;width:100%;"> <div style="width:2.5%;float:left;"> </div> <div style="width:20%;float:left;background-color:orange;margin:0 auto 0 auto;">s</div> <div style="width:5%;float:left;"> </div> <div style="width:20%;float:left;background-color:red;margin:0 auto 0 auto;">s</div> <div style="width:5%;float:left;"> </div> <div style="width:20%;float:left;background-color:green;margin:0 auto 0 auto;">s</div> <div style="width:5%;float:left;"> </div> <div style="width:20%;float:left;background-color:blue;margin:0 auto 0 auto;">s</div> <div style="width:2.5%;float:left;"> </div> <div style="clear:both;"></div> </div> </div> </body> Code (markup): And the result was perfect.
Or without the Spacers and using Half of the Div's: <body> <div style="margin:0 auto;text-align:center;width:100%;"> <div style="border:1px solid #000;margin:auto;width:100%;"> <div style="width:20%;float:left;background-color:orange;margin:0 5% 0 2.5%;">s</div> <div style="width:20%;float:left;background-color:red;margin:0 5% 0 auto;">s</div> <div style="width:20%;float:left;background-color:green;margin:0 5% 0 auto;">s</div> <div style="width:20%;float:left;background-color:blue;margin:0 2.5% 0 auto;">s</div> <div style="clear:both;"></div> </div> </div> </body> Code (markup):
Hmmm, as I understand it, the reason we can't both float and center something is that floats don't auto-margin. You can set margins in percents as above, but if you say "auto" they just collapse (the numeric ones wouldn't).