1

Why am I unable to see the top and bottom margins when I preview the div in Safari/Chrome/Firefox when I have set the margin to 50px.

HTML:

<div style="width:400px;background-color:#ffffaa">
  <p style="background-color:#aaffff;
            padding:20px;
            margin:50px;
            border-style:solid;
            border-width:5px;
            border-color:#000000;"> Text goes here ……… 
  </p>
</div>
Mark
  • 6,762
  • 1
  • 33
  • 50
Cool Brian
  • 21
  • 7

3 Answers3

0

This behavior is normal as specified in the CSS box model:

8.3.1 Collapsing margins

In this specification, the expression collapsing margins means that adjoining margins (no padding or border areas separate them) of two or more boxes (which may be next to one another or nested) combine to form a single margin.

In CSS2, horizontal margins never collapse.

Vertical margins may collapse between certain boxes:

Two or more adjoining vertical margins of block boxes in the normal flow collapse. The resulting margin width is the maximum of the adjoining margin widths. In the case of negative margins, the absolute maximum of the negative adjoining margins is deducted from the maximum of the positive adjoining margins. If there are no positive margins, the absolute maximum of the negative adjoining margins is deducted from zero. Vertical margins between a floated box and any other box do not collapse. Margins of absolutely and relatively positioned boxes do not collapse.

To achieve your goal you must set top and bottom padding to the parent element, the div in your case.

Community
  • 1
  • 1
Catalin MUNTEANU
  • 5,618
  • 2
  • 35
  • 43
-1

I think what you are looking for is this:

<div style="width:400px;background-color:#ffffaa;padding:50px">
  <p style="background-color:#aaffff;
            padding:20px;
            border-style:solid;
            border-width:5px;
            border-color:#000000;
            display:block;"> Text goes here ……… 
  </p>
</div>
gmann1982
  • 97
  • 1
  • 9
-1

if you add a content to your div (lets say a space with &nbsp;) it solves the problem.

<div style="width:400px;background-color:#ffffaa">&nbsp;
  <p style="background-color:#aaffff;
        padding:20px;
        margin:50px;
        border-style:solid;
        border-width:5px;
        border-color:#000000;"> Text goes here ……… 
  </p>
</div>

But you're right, strange.

regards, Yann

Yann
  • 144
  • 3
  • 1
    It is not strange. This is the specified behavior: http://www.w3.org/TR/CSS21/box.html#collapsing-margins – Catalin MUNTEANU May 15 '14 at 12:09
  • Yes it is the spec behavior, which does not remove my feeling of being a strange behavior ;) – Yann May 15 '14 at 12:15
  • The top margin is taken into account as the paragraph element is 50px from the top, but the background color of parent div is not display. Which does not occurs for horizontal margin. I can easily understand Brian's question regarding this. – Yann May 15 '14 at 12:24