前端 - margin的问题,那个老哥帮我解释下
伊谢尔伦
伊谢尔伦 2017-04-17 14:53:40
0
5
997
<!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 不是应该被红色环绕吗?烦请那个老哥解释下。

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

reply all(5)
大家讲道理

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

Ty80

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.

Peter_Zhu

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

迷茫

Search for “child element margin affects parent element”

左手右手慢动作

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,或者加上透明边框就可以解决了。
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template