Floating Divs in Div

One of the basic fundamentals of CSS (as far as I can tell) is nesting divs. Maybe that is the wrong terminology for this, maybe its parent and child, I don’t know and I’m still learning so please forgive me CSS gods. Anyways, placing div(s) inside another div is fundamental to controlling your layout. There is one tricky part, a property that I keep leaving out. Let’s run through this:

CSS:

.outside-div {border: 2px solid blue; width: 400px; padding: 15px;}

.inside-div {border: 3px dotted pink; width: 90px; margin: 2px;}

HTML:

<div class=”outer-div”>

                <div class=”inner-div”></div>

</div>

No problems with this code! It should show a small box with a pink dotted border nested inside a much larger blue bordered box. So…what’s the big deal? OK, let’s suppose this is for a navigation menu so you add 2 more boxes (divs) to your HTML with text, like so:

HTML:

<div class=”outer-div”>

                <div class=”inner-div”>Learn HTML</div>

                <div class=”inner-div”>Learn CSS</div>

                <div class=”inner-div”>Learn JavaScript</div>

</div>

Wow! Again, no problems! You should have a nice vertical menu with three options. However, what if your design requires a horizontal menu? To make the pink dotted border boxes align horizontally you’ll have to add the float property to your CSS (to the inside div), like so:

CSS:

.outside-div {border: 2px solid blue; width: 400px; padding: 15px;}

.inside-div {border: 3px dotted pink; width: 90px; margin: 2px; float: left;}

The float property gets the elements to ‘float’ to the left, side by side of one another. Once you add float to the code though you’ll see that the pink boxes now fall outside of the blue box! This is the flash point that always trips me up. I’ll just be coding away with all my divs but once I start any kind of horizontal alignment with the float property things quickly get out of order.

To remedy this you have to add ‘overlfow: auto’ to your CSS:

CSS:

.outside-div {border: 2px solid blue; width: 400px; padding: 15px; overflow: auto;}

.inside-div {border: 3px dotted pink; width: 90px; margin: 2px; float: left;}

Once this is added your outer box (div) will behave like normal, encompassing the three pink bordered boxes in a horizontal row. You can get to know more about the overflow property here at W3Schools.