Reputation:
I have a two column layout, one of them is floated left, another is not:
<div id="left">
LEFT
</div>
<div id="right">
RIGHT
</div>
And the CSS is:
#left {
float: left;
width: 200px;
background: yellow;
}
#right {
margin-left: 200px;
background: orange;
}
In the right
element that is not floated, I have a markup like this:
<div id="nav">
<div class="item">LINK</div>
<div class="item">LINK</div>
<div class="item">LINK</div>
<div class="item">LINK</div>
<div class="item">LINK</div>
<div class="clear"></div>
</div>
<h1>Welcome World</h1>
And the CSS for nav
and item
is (as you see, the item
is floated):
#nav {
background: blue;
}
.item {
background: green;
float: left;
margin-right: 10px;
}
And my clear
element is:
.clear {
clear: both;
}
And, at last, I get this result:
I think that the problem is with my clear
element which is clearing the floated element too (#left
).
But I expected to get this result:
Upvotes: 4
Views: 372
Reputation: 59799
Instead of adding unneeded mark-up in your HTML, you can just add overflow: hidden;
to #nav
. This will create a new block-formatting context for the list-items within #nav
, as floated elements are taken out of the normal flow (its in-flow container won't respect their height, notice the <body>
not extending down to #left
in my fiddle)
From the Visual Formatting Model, 9.4.1:
Floats, absolutely positioned elements, block containers (such as inline-blocks, table-cells, and table-captions) that are not block boxes, and block boxes with 'overflow' other than 'visible' (except when that value has been propagated to the viewport) establish new block formatting contexts for their contents.
#nav {
background: blue;
overflow: hidden; /* Creates a new block-formatting context
for floated descendants */
}
Upvotes: 1
Reputation: 10525
Clearing floats are concerned with floated elements but you have cleared the element that you have not floated either left or right i.e.
#nav
. So addfloat: left;
to your#nav
then only your<div class="clear"></div>
will work as what you want.
Upvotes: 0
Reputation: 100351
Removed from #nav
<div class="clear"></div>
Added style to #nav
overflow: hidden;
Upvotes: 0
Reputation: 2260
I did this a different way. You can move the clear to one of two different places (which gets you different results), but the overall problem is solved. Pick whichever one is more suitable.
(http://jsfiddle.net/bJFUj/4/ OR http://jsfiddle.net/bJFUj/6/)
In both cases I basically change nav's css (because no background would show otherwise)
#nav {
background: blue;
overflow: hidden;
}
I'd just move the clear to the element containing both div#left
and div#right
. Putting it inside div#right
seems to be creating some interesting effects with regards to the height of div#right
.
Upvotes: 0
Reputation:
Make your #nav
element to inline-block
and set the width
to 100%
:
#nav {
background: blue;
display: inline-block;
width: 100%;
}
Upvotes: 1