Search code examples
htmlcssmargins

Why are my div margins overlapping and how can I fix it?


I don't understand why the margins of these divs are overlapping.

.alignright {float: right}
#header .social {margin-top: 50px;}
#header .social a {display: inline-block;}
#header .social .fb {width: 64px; height: 1px; padding-top: 60px; overflow: hidden;}
#header .social .twit {width: 64px; height: 1px; padding-top: 60px; overflow: hidden;}
#header .contact {margin: 20px 70px 20px 0; font-size: 14px; font-weight: bold;}
#header .contact span {color: #FFFFFF;}
#header .search {margin: 10px 0 0;}
<div class="alignright">
    <div class="social">
        <a href="#" class="twit"></a>
        <a href="#" class="fb"></a>
    </div><!-- social -->
    <div class="contact">
        Get in Touch: <span>+44 10012 12345</span>            
    </div><!-- contact -->
    <div class="search">
        <form method="post" action="">
            <input type="text" value="" name="s" gtbfieldid="28">
        </form>
    </div><!-- search -->
</div>

picture


Solution

  • I think it's a collapsed margin. Only the largest margin between the bottom of the first element and the top of the second is taken into account.

    It is quite normal to don't have too much space between two paragraphs eg.

    You cannot avoid that with two adjacent elements so you have to enlarge or reduce the larger margin.

    EDIT: cf. W3C

    Two margins are adjoining if and only if:

    • both belong to in-flow block-level boxes that participate in the same block formatting context
    • no line boxes, no clearance, no padding and no border separate them
    • both belong to vertically-adjacent box edges

    So there is no collapsing with float which takes the element out of the flow.