質問

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>
役に立ちましたか?

解決 2

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>

他のヒント

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.

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

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top