margin现象:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" type="text/css" href="1.css"/>
</head>
<body>
<div class="wrapper">
<div class="content"></div>
</div>
</body>
</html>
*{
margin: 0px;
padding: 0px;
}
.wrapper{
margin-left: 100px;
margin-top: 100px;
width: 100px;
height: 100px;
background-color: black;
}
.content{
width: 50px;
height: 50px;
background-color: green;
}
效果:
左右方向:
当我们在对子标签移动时,加入如(margin-left/right: 20px; ), 可以左右移动,
上下方向:
但当子类content中的margin-top: 小于或等于父类的margin-top: 时,则不会发生移动,
当子类content中的margin-top: 大于于父类的margin-top: 时,则子类和父类一起发生移动,两者之间的相对位置不变。
这种现象叫做margin塌陷。
解决方法:
{触发盒子的bfc (block format context);}
四种方法:
在样式中加入一下任意一种即可,解决,但各有弊端,根据需要取最适合的。
1.position: absolute;
2. float: left/right;
3.overflow: hidden;
4.display: inline-block;
如在父类中加入:position: absolute;
*{
margin: 0px;
padding: 0px;
}
.wrapper{
position: absolute;
margin-left: 100px;
margin-top: 100px;
width: 100px;
height: 100px;
background-color: black;
}
.content{
margin-top: 50px;
width: 50px;
height: 50px;
background-color: green;
}
即可解决。