Margin on child element moves parent element

前端 未结 14 2187
广开言路
广开言路 2020-11-21 23:38

I have a div (parent) that contains another div (child). Parent is the first element in body with no

14条回答
  •  一整个雨季
    2020-11-22 00:24

    Found an alternative at Child elements with margins within DIVs You can also add:

    .parent { overflow: auto; }
    

    or:

    .parent { overflow: hidden; }
    

    This prevents the margins to collapse. Border and padding do the same. Hence, you can also use the following to prevent a top-margin collapse:

    .parent {
        padding-top: 1px;
        margin-top: -1px;
    }
    

    Update by popular request: The whole point of collapsing margins is handling textual content. For example:

    h1, h2, p, ul {
      margin-top: 1em;
      margin-bottom: 1em;
    }

    Title!

    Title!

    Paragraph

    Title!

    Paragraph

    • list item

    Because the browser collapses margins, the text would appear as you'd expect, and the

    wrapper tags don't influence the margins. Each element ensures it has spacing around it, but spacing won't be doubled. The margins of the

    and

    won't add up, but slide into each other (they collapse). The same happens for the

    and

      element.

      Sadly, with modern designs this idea can bite you when you explicitly want a container. This is called a new block formatting context in CSS speak. The overflow or margin trick will give you that.

提交回复
热议问题