shubendrak
shubendrak

Reputation: 2068

Unexpected behavior of css float

Here is my jsFiddle

I just have 3 divs. The 2nd div is floated to the right, and 3rd div appears just below the 2nd.

In the 3rd div, I am setting margin-top property, and this property does not have any effect on the layout.

Question: Can someone explain me understanding this behavior of float?

HTML

<div class="header">
</div>
<div class="sidebar">
</div>
<div class="footer">
</div>

CSS

.header {
    width: 100%;
    height: 80px;
    background-color: #abcdef;
}

.sidebar {
    margin-top: 15px;
    float: right;
    width: 200px;
    height: 200px;
    background-color: #abcdef;
    display: block;
}

.footer {
    clear: both;
    margin-top: 20px;
    width: 100%;
    height: 60px;
    background-color: #000000;
}

Upvotes: 2

Views: 124

Answers (4)

Niels Keurentjes
Niels Keurentjes

Reputation: 41958

This is not unexpected at all. The .sidebar is removed from regular flow layout by its float property, as such it doesn't take up any space anymore. The .footer has a clear rule, so it is forced underneath any floats, but that automatically puts it 215px (margin+height of the sidebar) behind the last element that is part of the flow layout. As such its margin requirement of 20px is completely satisfied, and it appears at its logical current position. You can verify this by setting the top margin to 220px instead, it will appear 5px (220-215) below the sidebar.

You can easily achieve the effect you desire by putting margin-bottom:20px on the sidebar since it will then be required to keep that distance to the footer, pushing it down.

Upvotes: 5

mikeswright49
mikeswright49

Reputation: 3416

This is caused by the fact that floated elements aren't really there with respect to margin calculations. Your .footer is below whatever unfloated elements are above it, (with a margin of 20px). This issue is caused because margins with respect to floats are calculated relative to other floats, (not all other elements). So to get the desired effect add a margin-bottom element to .sidebar, have a meaningless float added to the .footer, or add a

<div style="clear:both"></div>

between the .footer and .sidebar

Upvotes: 0

Duncan Beattie
Duncan Beattie

Reputation: 2366

The top margin of the footer div is being collapsed, http://www.w3.org/TR/CSS21/box.html#collapsing-margins

If you add margin-bottom to the sidebar instead of the top of the footer it will work.

Upvotes: 0

David Ziemann
David Ziemann

Reputation: 970

The issue is related to the clear rule.

W3C - An element that has had clearance applied to it never collapses its top margin with its parent block's bottom margin.

Baiscally, if you want to use clear, the general rule is to add an element between the two floated divs to ensure you can correctly space them.

Upvotes: 1

Related Questions