margin的意思是元素的外边距区域值,即该元素外面要留白的距离。它的值可以设置为三种,一种是使用数值,例如:30px,还有一种是使用百分比(相对父元素的百分比),以及第三种:auto。
下面用代码和效果说话。
1,有如下结构
<body>
<div class="page">
<div class="container">
<div class="content"></div>
</div>
</div>
</body>
同时默认情况下的css如下
*{
padding: 0; margin: 0;
}
.page{
margin: 0px auto; height: 400px; width: 400px;
background: darkgoldenrod; overflow: hidden;
}
.container{
background: yellowgreen;
height: 200px; width: 200px;
}
.content{
background: yellow;
width: 100px; height: 100px;
}
展示效果(图1)
接着给content添加margin-top,最后样式如下
.content{
background: yellow;
width: 100px; height: 100px;
margin-top: 40%;
}
显示效果(图2)
可见,content和container元素向下移动80px(.container高度的百分之四十),之所以会这样是因为此时设置了marging的.content元素是针对最近的BFC来定位的,而最近的BFC是.page而不是父元素.container ,所以导致了外边距重叠使得.container的margin-top的值与.container相同(40%算出后的具体的值)。
那么要针对父元素(.container),则只需设置.container的overflow即可,这样就可以消除外边距重叠的问题,例如:
.container{
background: yellowgreen;
height: 200px; width: 200px;
overflow: hidden;
}
其运行结果如下(图3)
那如果现在去掉.content的margin-top改为margin-bottom会怎么样呢,例如:
.content{
background: yellow;
width: 100px;
height: 100px;
/*margin-top: 40%;*/
margin-bottom: 30px;
}
其结果(图4)
可见并未起到任何的作用,是不是说明marging-bottom真的没起用呢?答案是否定的!上面展示的是一种父子嵌套的结构,那如果再多一个兄弟元素会如何?
现在给.content元素添加一个兄弟元素,如下:
<body>
<div class="page">
<div class="container">
<div class="content"></div>
<div class="content2"></div>
</div>
</div>
</body>
添加content2的样式如下:
.content2{
width: 100px;
height: 30px;
background: cyan;
}
(图5)
接下来再给.content添加margin-top的样式
.content{
background: yellow;
width: 100px;
height: 100px;
margin-top: 5px;
margin-bottom: 30px;
}
效果(图6)
接着再给.content添加一个兄弟节点
<body>
<div class="page">
<div class="container">
<div class="content3"></div>
<div class="content"></div>
<div class="content2"></div>
</div>
</div>
</body>
加上css如下:
.content3{
width: 100px;
height: 15px;
background: cyan;
}
运行效果(图7)
可见margin-bottom确实是起到作用的,"图4"之所以看不出效果,那是因为其实margin是针对兄弟元素间的,只是上面的例子中,一开始.content元素在top方向没有兄弟元素,就与父元素”外边距重叠“了(当然兄弟元素间也会外边距重叠,上面的例子没有体现这点)。那bottom又为什么没外边距重叠啊?因为默认的文档流是从上至下,从左至右排列的。
转载于:https://blog.51cto.com/dengshuangfu/1713937