在设置子类和父类之间的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;/*成功*/
}