给子元素加margin-top在父元素上自作用解决办法

我们在随便给一个div加margin-top的时候会给父元素起作用。类似的margin-left就不会。
栗子:
html

<div class=box>
         <div class="son"></div>
     </div>

css

.box{
            width:200px;
            height: 200px;
            background: lightsalmon;
        }
        .son{
            width:100px;
            height: 100px;
            background: lightblue;
            margin-left:50px;
            margin-top: 50px;
        }

产生的结果就是
在这里插入图片描述
原因是
一个盒子如果没有上补白(padding-top)和上边框(border-top),那么这个盒子的上边距会和其文档流中的第一个子元素的上边距重叠。

解决方法
方法一、给父元素的样式加 overflow=hidden

.box{
            width:200px;
            height: 200px;
            background: lightsalmon;
            overflow: hidden;
        }

方法二

.box{
            width:200px;
            height: 200px;
            background: lightsalmon;
            padding: 1px;
        }

方法三

.box{
             width:200px;
             height: 200px;
             background: lightsalmon;
             border: 1px solid white;
         }

效果
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Alive_tree/article/details/105710995