为什么 Safari 4 / mac 不渲染此嵌套 div 中的顶部和底部边距?
Safari 4 似乎会忽略元素边距,除非我添加边框。
以下示例呈现左右边距,但不呈现顶部或底部。
添加边框后,它会按预期呈现。我是否做错了什么,或者我是否必须为 Safari 的每个带有边距的元素添加边框 (尽管是透明的)
?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>testing</title>
<style>
body {background-color:#666;}
div {display:block; position:relative; margin:0; padding:0;}
.background {background-color:#990000;}
.foreground {background-color:#fff; margin:10px; padding:10px;}
</style>
</head>
<body>
<div class='background'>
<div class='foreground'>
foreground
</div>
</div>
</body>
</html>
Safari 4 seems to be ignoring element margins unless I add a border.
The following example renders left and right margins but no top or bottom.
Upon adding a border, it renders as expected. Am I doing something wrong or am I going to have to add borders (albeit transparent ones)
to every element with margins just for Safari?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>testing</title>
<style>
body {background-color:#666;}
div {display:block; position:relative; margin:0; padding:0;}
.background {background-color:#990000;}
.foreground {background-color:#fff; margin:10px; padding:10px;}
</style>
</head>
<body>
<div class='background'>
<div class='foreground'>
foreground
</div>
</div>
</body>
</html>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一种正常的奇怪行为,称为保证金(已编辑,对不起,我是法国人)崩溃。
为了避免这种情况,请在容器上添加
overflow:auto;
。It's a normal weird behaviour calling margin (edited, sorry i'm french) collapse.
To simply avoid it add
overflow:auto;
on the container.这称为边距崩溃。当顶部和底部边距相互接触时,边距将合并为两者中较大的一个。
添加边框时它“正确”工作的原因是因为您为边距创建了 1px 分隔符,因此它们不再折叠。有趣的是,如果您添加一个没有高度/边框的空 div,边距仍然会折叠,因为该 div 占用了 0px 空间。
It is called margin collapse. When a top and bottom margin are touching each other, the margins will combine into the greater of the two.
The reason it works "correctly" when you add the border is because you created a 1px separator for the margins so they no longer collapse. Interestingly, if you instead added a empty div with no height/borders, the margins would still collapse because the div takes up 0px space.