为什么我的边距会崩溃,即使我的所有东西都有边界?
代码如下:
<html>
<head>
<title></title>
<style type="text/css">
* {border: 0px; padding: 0px;}
#greenbox
{
margin: 20px;
border: 5px solid green;
}
#redbox
{
margin: 20px;
border: 5px solid red;
}
#bluebox
{
border: 5px solid blue;
margin-left: 20px;
margin-right: 20px;
margin-bottom: 20px;
margin-top: 20px; /*COLLAPSES - why??*/
}
</style>
</head>
<body>
<div id="greenbox">
<div id="redbox">
red box
</div>
<div id="bluebox">
bluebox
</div>
</div>
</body>
</html>
基本上,它是一个绿色盒子,里面包含一个红色盒子和一个蓝色盒子。
为什么红框和蓝框之间的垂直间距不是 40px?
我知道红框的下边距和蓝框的上边距已经“塌陷”,但它是我的理解是,如果你有边框或填充,边距不会折叠(我已经尝试过两者 - 仍然是相同的结果。
Here is the code:
<html>
<head>
<title></title>
<style type="text/css">
* {border: 0px; padding: 0px;}
#greenbox
{
margin: 20px;
border: 5px solid green;
}
#redbox
{
margin: 20px;
border: 5px solid red;
}
#bluebox
{
border: 5px solid blue;
margin-left: 20px;
margin-right: 20px;
margin-bottom: 20px;
margin-top: 20px; /*COLLAPSES - why??*/
}
</style>
</head>
<body>
<div id="greenbox">
<div id="redbox">
red box
</div>
<div id="bluebox">
bluebox
</div>
</div>
</body>
</html>
Basically, it's a green box, which contains a red box and a blue box inside it.
Why isn't the vertical space between the red box and blue box 40px?
I understand that the bottom-margin of the red box and the top margin of the blue box have 'collapsed', but it was my understanding that margins do not collapse if you have a border, or padding (I've tried both - still the same result.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
边距不会因边界而塌陷。他们确实彼此崩溃。
请参阅此示例:
当存在边框时,蓝色 div 顶部的边距将蓝色 div 的顶部推离其内部的红色 div 的顶部。当边框不存在时,边距会穿过边缘并折叠到红色 div 周围的边距中。
您的两个边距相互接触,之间没有边界 - 所以它们会折叠。
Margins do not collapse through borders. They do collapse through each other.
See this example:
When the border is present, the margin on the top of the blue div pushes the top of the blue div away from the top of the red div that it is inside. When the border is not present, the margin goes through the edge and collapses into the margin around the red div.
Your two margins are touching each other with no border between them — so they collapse.
边距在盒模型中位于边框之外,因此边框与折叠的边距无关。
您可以在此处阅读盒模型: http://www.w3.org/TR /CSS21/box.html
您可以在此处阅读折叠边距:http://www.w3.org/TR/CSS21/box.html#collapsing-margins
Margins are outside border in the box model, thus the borders have nothing to do with margins that collapse.
You can read up on the box model here: http://www.w3.org/TR/CSS21/box.html
You can read up on collapsing margins here: http://www.w3.org/TR/CSS21/box.html#collapsing-margins