Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having issues with floating divs in HTML using the CSS property "float"?

I have an issue with my divs. I currently have four “divs” in html that look like below. What I want to do is have everything in my page inside the “page” div. Inside the “main” div I have the “content” and “side” div and both have the “float:left” property from CSS. What’s happing is that when I do this I lose the background of my “page” div which is white. How can I prevent this and create my content and side divs? I know this is easy but for some reason I’m not getting it right. Any help will be appreciated.

Thanks

<div id=”page”>
   <div id=”container”>
   </div>
   <div id=”main”>
      <div id=”content”>
      </div>
      <div id=”side”>
      </div>
   </div>
</div>

This is my CSS code

#page 
{
margin: 2em auto;
max-width: 1000px;
background-color:#fff;
}

#main
{
clear: both;
padding: 1.625em 0 0;
width:700px;
}

#content 
{
clear: both;
padding: 1.625em 0 0;
width:740PX;;
float:left;
}

#side
{
width:250px;
margin:5px;
float:left;
}
like image 421
jorame Avatar asked Nov 22 '25 23:11

jorame


2 Answers

The reason you lose the background of your div is because it only contains floating content, which causes it to have no height. Once something "clears" the floats, it will occupy space again. Try adding this after your main div (you can have the style in the style sheet instead):

<div style="clear: both;"></div>
like image 52
Jacob Avatar answered Nov 25 '25 16:11

Jacob


You need to contain your floats. When you float an element, it takes it out of the document flow, so any parent container will just collapse if you don't tell it to contain the child floats.

To contain child floats, the easiest is to apply overflow: auto.

So try this:

#page {
    margin: 2em auto;
    max-width: 1000px;
    background-color:#fff;
    overflow: auto;
}
like image 27
DA. Avatar answered Nov 25 '25 15:11

DA.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!