Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Background color for div with child divs

<html>
<head>
<style type="text/css">
div
{
background-color:#ccc;
}
</style>
</head>

<body>
<div>
<div style="float: left;">This is a text inside a div element.</div>
<div style="float: right;">We are still in the div element.</div>
</div>

</body>
</html>

Why isnt the background color showing up in between those 2 divs? Output after running this page

like image 306
Null Head Avatar asked Dec 05 '11 23:12

Null Head


2 Answers

When you float elements you should provide the width of the floated elements. Otherwise you may encounter unexpected behaviors accross different browsers.

Check this tutorial, there is good info on floating in css. [link is dead]

Basically, if you provide an overflow:hidden; to the container div and provide width to the floated elements, your problem will be solved.

<div style="overflow: hidden;">
  <div style="float:left; width: 300px;">Some text</div>
  <div style="float:right; width: 300px;">Some text</div>
</div>

Similarly, you can add another div wherever you want to normalize the flow ike this:

<div>
  <div style="float:left; width: 300px;">Some text</div>
  <div style="float:right; width: 300px;">Some text</div>
  <div style="clear:both;"></div>
  <div>This div will be at the same place 
       as if the previous elements are not floated</div>
</div>

Both will work :)

EDIT

Another method which I use frequently in these days is to float the first element and set a margin-left to the following element. For instance:

<div>
    <div style="float: left; width: 300px;">Some text</div>
    <div style="margin-left: 300px;">Some text</div>
    <div style="clear: both;"></div>
</div>

The advantage of this method is that the following element (the second div in this case) does not need a fixed width. Plus, you may skip the third div (clear: both;). It's optional. I just add it in case that the floated div is longer in height than the second div since if you don't add it the parent div will always get the height of the second div.

like image 84
Savas Vedova Avatar answered Nov 09 '22 01:11

Savas Vedova


Just set the container div to overflow: hidden;.

If you set elements to float they won't be in the normal 'flow' of the document anymore.

div { background: #ccc; overflow: hidden; }

And you didn't even made a freehand circle ;)

like image 20
PeeHaa Avatar answered Nov 09 '22 01:11

PeeHaa