Small padding, big difference

后端 未结 7 1687
夕颜
夕颜 2021-01-05 06:26

If I only add a 1px padding to a div around a heading, then this makes apparently a huge difference (http://jsfiddle.net/68LgP/).

html:

相关标签:
7条回答
  • 2021-01-05 06:57

    It's to do with the default CSS applied to Heading1 element. It already has a padding/margin applied to it.

    If you reset it, you can see the result you're after: http://jsfiddle.net/68LgP/8/.

    h1 { padding: 0; margin: 0; }
    .pad0 {
        background-color: #E9E9E9;
        padding: 0px;
    }
    .pad1 {
        background-color: #E9E9E9;
        padding: 1px;
    }
    
    0 讨论(0)
  • 2021-01-05 06:57

    Please see the updated CSS here

    .pad0 {
        background-color: #E9E9E9;
        padding: 0px;
        margin: 0px;
    }
    .pad1 {
        background-color: #E9E9E9;
        padding: 1px;
        margin: 0px;
    }
    
    h1
    {
        padding: 0px;
        margin: 0px;
    }
    
    0 讨论(0)
  • 2021-01-05 07:19

    This is due to the margin collapsing

    Top and bottom margins of blocks are sometimes combined (collapsed) into a single margin whose size is the largest of the margins combined into it, a behavior known as margin collapsing.

    You can find further information also on w3c site.

    Two margins are adjoining if and only if [...] no line boxes, no clearance, no padding and no border separate them [...]

    So if you apply a padding-top (1px is enough), as in your second example, the margins are no longer collapsed. An easy solution, as already suggested, is to remove the default margin of your heading elements and apply a padding instead.

    0 讨论(0)
  • 2021-01-05 07:19

    <div> is a block element, which means that it both starts and ends with a line break. I beleive that this is contributing to your problem - you may want to swap to <span> tags, although I'm not sure if this will solve the problem.

    0 讨论(0)
  • 2021-01-05 07:20

    You could use CSS Reset which resets all CSS settings, including this kind of problems. Recommended for any site.
    How can CSS Reset file solve your problem? As you can see, in the first paragraph, h1 is included, and it's given margin:0 which is needed for reducing the difference in problems like yours.

    0 讨论(0)
  • 2021-01-05 07:21

    set h1 margin to 0

    h1 {
        margin: 0;
    }
    
    0 讨论(0)
提交回复
热议问题