给第一个子元素加margin-top,父元素会向下移动的解决办法


给第一个子元素设置margin-top上外边距时,父元素总会跟着向下移动。

<div id="parent">
    <div id="son"></div>
</div>
<style>
    body{
        margin: 0;
        padding: 0;
        background-color: grey;
    }
    #parent{
        width: 200px;
        height: 200px;
        background-color: red;
    }
    #son{
        width: 100px;
        height: 100px;
        background-color: green;
        margin-top: 50px;
    }
</style>

页面效果:

这是margin外边距坍塌导致的,按照css规范,两个相邻的元素之间的margin值会共用较大的那一个,而如果没有上边框或上内间距,嵌套的元素之间和同级的元素一样满足使用这个规范的条件,父元素会拥有子元素一样的上外边距。要解决这个问题其实也非常简单,这里给出四种不同的解决方法。

方法一:给父元素加overflow:hidden

<div id="parent">
    <div id="son"></div>
</div>
<style>
    body{
        margin: 0;
        padding: 0;
        background-color: grey;
    }
    #parent{
        width: 200px;
        height: 200px;
        background-color: red;
        overflow: hidden;
    }
    #son{
        width: 100px;
        height: 100px;
        background-color: green;
        margin-top: 50px;
    }
</style>

效果如图:

方法二:给父元素加border:1px solid transparent

<div id="parent">
    <div id="son"></div>
</div>
<style>
    body{
        margin: 0;
        padding: 0;
        background-color: grey;
    }
    #parent{
        width: 200px;
        height: 200px;
        background-color: red;
        border-top: 1px solid transparent;
    }
    #son{
        width: 100px;
        height: 100px;
        background-color: green;
        margin-top: 50px;
    }
</style>

效果如图:

方法三:父元素或子元素浮动

<div id="parent">
    <div id="son"></div>
</div>
<style>
    body{
        margin: 0;
        padding: 0;
        background-color: grey;
    }
    #parent{
        width: 200px;
        height: 200px;
        background-color: red;
        float: left;
    }
    #son{
        width: 100px;
        height: 100px;
        background-color: green;
        margin-top: 50px;
        /* float: left; */      /* 浮动加在子元素上也可以 */
    }
</style>

效果如图:

方法四:父元素加padding-top:1px

<div id="parent">
    <div id="son"></div>
</div>
<style>
    body{
        margin: 0;
        padding: 0;
        background-color: grey;
    }
    #parent{
        width: 200px;
        height: 200px;
        background-color: red;
        padding-top: 1px;
    }
    #son{
        width: 100px;
        height: 100px;
        background-color: green;
        margin-top: 50px;
    }
</style>

效果如图:

写在最后

以上为全部内容,感谢阅读。
本博文仅为学习记录和分享交流,如有错漏,还请帮忙指出,也欢迎更多补充,不胜感激。

GitHub地址:https://github.com/ljxlijiaxin.

posted @ 2021-01-19 13:54  以休伯利安的名义  阅读(325)  评论(0编辑  收藏  举报