margin的塌陷现象
标准文档流中,竖直方向的margin不叠加,以较大的为准。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style type="text/css">
.first{
width: 300px;
height:300px;
background-color: red;
margin-bottom: 100px;
}
.second{
width: 300px;
height:300px;
margin-top: 200px;
background-color: yellowgreen;
}
</style>
</head>
<body>
<div class="first">
</div>
<div class="second">
</div>
</body>
</html>
所以间距是200px。
如果不在标准流,比如盒子都浮动了,那么两个盒子之间是没有塌陷现象的:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Document</title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
div{
width: 200px;
border: 10px solid red;
overflow: hidden;
}
.p1{
width: 200px;
height: 100px;
background-color: orange;
margin-bottom: 40px;
float: left;
}
.p2{
width: 200px;
height: 100px;
background-color: orange;
margin-top: 30px;
float: left;
}
</style>
</head>
<body>
<div>
<p class="p1"></p>
<p class="p2"></p>
</div>
</body>
</html>
盒子居中margin:0 auto;
margin
的值可以为auto
,表示自动。当left
、right
两个方向,都是auto的时候,盒子居中了:
div{
margin-left: auto;
margin-right: auto;
width: 200px;
border: 10px solid red;
overflow: hidden;
}
等价于
div{
margin: 0 auto;
width: 200px;
border: 10px solid red;
overflow: hidden;
}
注意
- 使用
margin:0 auto;
的盒子,必须有width
,有明确的width
- 只有标准流的盒子,才能使用
margin:0 auto;
居中。也就是说,当一个盒子浮动了、绝对定位了、固定定位了,都不能使用margin:0 auto;
。 margin:0 auto
;是在居中盒子,不是居中文本。文本的居中,要使用text-align:center;
善于使用父亲的padding,而不是儿子的margin
如果父亲没有border,那么儿子的margin
实际上就是给父亲设置margin
。所以,父亲整体也掉下来了。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Document</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
div {
margin: 0 auto;
width: 300px;
height: 300px;
background-color: red;
}
.p1 {
width: 200px;
height: 100px;
background-color: orange;
}
</style>
</head>
<body>
<div>
<p class="p1"></p>
</div>
</body>
</html>
效果如图所示
我们给p1
这是margin
.p1 {
margin-top: 30px;
width: 200px;
height: 100px;
background-color: orange;
}
可以看到margin
设置给了父亲div
。现在我们给div
设置border
。
div {
margin: 0 auto;
width: 300px;
height: 300px;
background-color: red;
border: 5px solid blueviolet;
}
可以看到这次margin
真正作用到儿子身上了。margin
这个属性,本质上描述的是兄弟和兄弟之间的距离; 最好不要用这个marign
表达父子之间的距离。所以,我们一定要善于使用父亲的padding
,而不是儿子的margin
。