Home  >  Q&A  >  body text

前端 - margin的问题,那个老哥帮我解释下

<!DOCTYPE html>
<html lang="en">
<head>
    <title>test</title>
    <style type="text/css">
        * {
            margin: 0;
            padding: 0;
        }

        .a{
            height:48px;
            background: #eee;
        }

        .b{
            height:520px;
            background: #ff4949;
        }

        .c{
            width:90%;
            height:300px;
            margin:20px auto;
            background: #fff;
        }
    </style>
</head>
<body>
<p class="a"></p>
<p class="b">
    <p class="c"></p>
</p>

</body>
</html>

p.c 不是应该被红色环绕吗?烦请那个老哥解释下。

伊谢尔伦伊谢尔伦2728 days ago951

reply all(5)I'll reply

  • 大家讲道理

    大家讲道理2017-04-17 14:55:40

    Because in BFC, two adjacent (brothers or father-son), no borders and no padding, the margin-top of an element and the margin-top of its first regular document flow child element will produce margin-collapse (outer margin from folding).

    You add a border to b,

    border: 1px solid transparent;

    Or add padding,

    padding: 1px 0;

    can be eliminated.

    Alternatively, you can add overflow: hidden; to b.

    You can refer to: In-depth understanding of BFC and Margin Collapse

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 14:55:40

    Just add overflow: hidden; in .b.

    Because overflow uses values ​​other than visible (hidden, auto, scroll) will trigger BFC.
    What is BFC?
    Block Formatting Contexts (block-level formatting context)
    Elements with BFC can be regarded as isolated independent containers. The elements inside the container will not affect the layout of the outside elements, and BFC has ordinary containers. There are some features that it does not have, such as the ability to contain floating elements. The second type of float clearing method mentioned above (such as the overflow method) triggers the BFC of the parent element of the floating element, so that it can contain floating elements, thereby preventing height collapse. problem.

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 14:55:40

    overflow: hidden; You add this sentence to p.b.

    reply
    0
  • 迷茫

    迷茫2017-04-17 14:55:40

    Search for “child element margin affects parent element”

    reply
    0
  • ringa_lee

    ringa_lee2017-04-17 14:55:40

    This is called overlapping margins. The margins of the child elements will affect the parent elements, and the larger the margins of the two, the larger the margins of the entire container. At this time, you should choose to trigger BFC. The previous ones have made it very clear what BFC is. The situations that trigger BFC are:

    • Root element

    • float attribute is not none;

    • position is absolute or fixed;

    • display is inline-block, table-cell, table-caption, flex, inline-flex;

    • overflow is not visible;

    Solution:

    如果你给父级加上overflow:hidden,或者加上透明边框就可以解决了。
    

    reply
    0
  • Cancelreply