无法弄清楚为什么背景颜色包括边距!
代码如下:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title></title>
<style type="text/css">
* {border: 0px; padding: 0px;}
#greenbox
{
margin: 20px;
border: 5px solid green;
}
#redbox
{
background-color: red;
margin: 20px;
float:left;
width:50%;
}
#bluebox
{
background-color: blue;
margin: 20px;
width: 50%;
}
</style>
</head>
<body>
<div id="greenbox">
<div id="redbox"> red box </div>
<div id="bluebox"> blue box </div>
</div>
</body>
</html>
根据 W3C 页面,背景颜色应该只为内容、填充和边框区域“着色”;不是边距。然而,尽管红框和蓝框文本之间有 20px 边距
,但由于某种原因,蓝框的背景颜色似乎包括了上边距。我理解边距折叠的概念,但它在这里似乎没有意义。
有人能弄清楚发生了什么事吗?
Here is the code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title></title>
<style type="text/css">
* {border: 0px; padding: 0px;}
#greenbox
{
margin: 20px;
border: 5px solid green;
}
#redbox
{
background-color: red;
margin: 20px;
float:left;
width:50%;
}
#bluebox
{
background-color: blue;
margin: 20px;
width: 50%;
}
</style>
</head>
<body>
<div id="greenbox">
<div id="redbox"> red box </div>
<div id="bluebox"> blue box </div>
</div>
</body>
</html>
According to the W3C page, background-color should only 'color' the content, padding, and border area; not the margins. Yet although there is a 20px margin
between the red box and blue box text, it seems the background color of the blue box is including the top margin for some reason. I understand the concept of collapsing margins but it doesn't seem to make sense here.
Can anybody figure out what's going on?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
id“redbox”上的底部边距被忽略的原因是它向左浮动。如果您删除浮动,您将看到边距受到尊重。
如果您确实要求“redbox”浮动,那么您可以在“bluebox”上指定“clear:both”以使边距得到尊重。
一般来说,任何浮动的东西都需要随后清除。
The reason the bottom margin is being ignored on the id "redbox" is because it is floated left. If you remove the float the you will see the margin is respected.
If you did require "redbox" to be floated, then you could specify "clear:both" on "bluebox" to get the margins to be respected.
Generally anything that is floated needs to be cleared afterwards.
我认为您需要在
#redbox
和#bluebox
上使用“overflow:hidden
”。I think you need "
overflow: hidden
" on#redbox
and#bluebox
.这是因为
#redbox
是浮动的。删除float: left
以查看您的期望。It's because
#redbox
is floated. Remove thefloat: left
to see what you expect.我想通了。
如果您在蓝色框周围设置边框,您会发现蓝色框实际上位于红色框后面,大概是因为红色框是浮动的,因此不符合正常流程。
解决方案是使用
overflow: auto
声明。I figured it out.
If you set a border around the blue box, you will realise that the blue box is actually BEHIND the red box, presumably because the red box is floating and therefore out of the normal flow.
The solution is to use the
overflow: auto
declaration.