html+css margin塌陷

在设置子类和父类之间的margin-top时,会出现无反应的现象。
如下面代码:
html:

<!DOCTYPE html>
<html>
<head>
    <title></title>
<link rel="stylesheet" href="1.css">
<style type="text/css">

</style>
</head>

<body>
    <div class="wrapper">
        <div class="content"></div>
    </div>
</body
</html>

给父类设置margin-top, margin-left 父类会带着子类一起移动。
css:

*{
    padding: 0;
    margin: 0;
}
.wrapper{
    width: 100px;
    height: 100px;
    background-color: green;
    margin-top: 100px;
    margin-left: 100px;
}
.content{
    width: 50px;
    height: 50px;
    background-color: orange;
}

这里写图片描述
下面来设置子类相对父类之间的间距:

.content{
    width: 50px;
    height: 50px;
    background-color: orange;
    margin-left: 50px;//添加左边距==成功
    }

这里写图片描述

添加上边距:

.content{
    width: 50px;
    height: 50px;
    background-color: orange;
    /*margin-top: 50px;上边距====失败,无反应*/
    margin-top: 150px;/*成功===连同父级一起移动距上边距150px*/
}

结论:
子类设置margin-top 无法相对于父级来设置,只能相当于上窗口,而且,当二者都设置margin-top时,谁的值大就用谁的值。
这就称为margin塌陷
解决办法:
bfc(block format context)方法:
如何触发一个盒子的bfc?(添加在父级里)
1. position: absolute;
2.display: inline-block;
3.overflow: hidden;
4.float: left/right;
在实际开发中根据具体的情况来用不同的方法,每个方法都有其副作用。

解决后的代码:

css:

.wrapper{
    width: 100px;
    height: 100px;
    background-color: green;
    margin-top: 100px;
    margin-left: 100px;
    overflow: hidden;/*超出部分隐藏*/
    /*position: absolute;*/
    /*display: inline-block;*/  
    /*float: left/right;*/
}
.content{
    width: 50px;
    height: 50px;
    background-color: orange;
    margin-top: 50px;/*成功*/
}

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值