盒模型的外边距重叠

301 阅读1分钟

什么是css的盒模型呢?

一个盒模型包括四个部分: margin(外边距),padding(内边距),content(内容),border(边框) 如下图所示

image.png

常规块盒子有一种机制叫外边距折叠,即垂直方向上的两个外边距相遇时,会折叠成一个外边距,且折叠之后的外边距高度为两者之中较大的那一个。现在给类名为"left"、"right"两个盒子都设置宽度、高度且都为"100px"、都设置外边距且都为"10px",可以添加任意颜色便于区分两个盒子。此时通过调试工具可以发现两个盒子之间的距离为"10px",并不是"20px",说明已经发生了外边距折叠。

<style type="text/css">
            * {
                margin: 0;
                padding: 0;
            }
            .left,.right{
                width:100px;
                height:100px;
                margin:10px;
                background-color:pink;
            }
            
            
        </style>
    </head>
    <body>
        <section class="left"></section>
        <section class="right"></section>
    </body>

会发现两个盒子是标准流排列盒子,而且两个盒子之间外边距margin发生了重叠,那么怎么清除外边距重叠呢?

image.png

外边距折叠好像很奇怪,实际上却很有用。当一个页面包含了多个段落,如果没有外边距折叠,从第二个段落开始,所有段落的间距都是最上方段落的上外边距的两倍,有了外边距折叠,段落间距才会相等。 如果想要清除两个盒子之间的外边距折叠,可以给目标盒子设置以下属性: 1. display: inline-block 我们可以设置display:inline-block属性来清除外边距重叠

<style type="text/css">
            * {
                margin: 0;
                padding: 0;
            }
            .left,.right{
                display:inline-block;
                width:100px;
                height:100px;
                margin:10px;
                background-color:pink;
            }
            
            
        </style>
    </head>
    <body>
        <section class="left"></section>
        <section class="right"></section>
    </body>

效果如图所示:

image.png

2. float属性值不是"none"的元素

<style type="text/css">
            * {
                margin: 0;
                padding: 0;
            }
            .left,.right{
                float:left;
                width:100px;
                height:100px;
                margin:10px;
                background-color:pink;
            }
            
            
        </style>
    </head>
    <body>
        <section class="left"></section>
        <section class="right"></section>
    </body>

image.png

3. 绝对定位

<style type="text/css">
            * {
                margin: 0;
                padding: 0;
            }
            .left,.right{
               
                width:100px;
                height:100px;
                margin:10px;
                background-color:pink;
            }
            .right{
                position:absolute;
            }
            
        </style>
    </head>
    <body>
        <section class="left"></section>
        <section class="right"></section>
    </body>

现在给类名为"bottom"的盒子设置"position"属性为"absolute",可以看到下方的盒子向下移动了,此时外边距折叠失效。

image.png