首页 > css定位问题

css定位问题

为什么当设置子元素的margin时父元素会跟随向下动,父元素设置的是relative,后来只好用absolute定位子元素。请问出现这种情况的原因有哪些?已经是第二次遇到这种情况了。
<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="UTF-8">
<title>test</title>
<style>
    #father{
        width: 700px;
        height:700px;
        margin:30px auto;
        position: relative;
        background: yellow;
    }
    #one{
        width: 300px;
        height: 300px;
        background: blue;
        position: absolute;
        top:10px;
        left:20px;
    }
    #two{
        width: 300px;
        height: 300px;
        background: red;
        margin-top: 50px;
    }
</style>
</head>

<body>

<div id="father">
    <div id="one">1</div>
    <div id="two">2</div>
</div>

</body>
</html>


你父级需要设置oveflow:hidden. 就不会往下动了。 这个问题很常见。


能贴代码吗?按照我的理解,子元素设置margin一般是撑大父元素的,我不知道你说的父元素会跟随向下动是什么意思,把代码贴上来吧,好分析


你这个问题是margin collapse(外边距塌陷);解决的方法有三种:
1给父元素设置一个边框,当然可以设置边框为透明;
2.为父元素添加padding;
3:为父元素设置overflow:hidden;


子元素设置 margin 肯定会撑大父元素宽高啊


父级添加overflow:hidden……就解决了

【热门文章】
【热门文章】