给第一个子元素加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值会共用较大的那一个,而若是没有上边框或上内间距,嵌套的元素之间和同级的元素同样知足使用这个规范的条件,父元素会拥有子元素同样的上外边距。要解决这个问题其实也很是简单,这里给出四种不一样的解决方法。css

方法一:给父元素加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>

效果如图:
html

方法二:给父元素加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>

效果如图:
git

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

<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>

效果如图:
github

方法四:父元素加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>

效果如图:
学习

写在最后

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

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

相关文章
相关标签/搜索