我有一个包含 2 个 div 的页面。第一个是 float 的。第二个有一个“明确:两者”的 CSS 声明和一个大的上边距。但是,当我在 Firefox 或 IE8 中查看页面时,我看不到上边距。看起来第二个 div 正在接触第一个 div,而不是分开。有什么方法可以使 top margin 正常工作?
我已经阅读了 CSS 规范并注意到它说“由于 float 不在流中,因此在 float 框之前和之后创建的非定位 block 框垂直流动,就好像 float 不存在一样。”。但是,我不知道该怎么做。
这是一个例子:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>CSS test</title>
</head>
<body>
<div style="float: left; border: solid red 1px">foo</div>
<div style="clear: both; margin-top: 90px; border: solid red 1px">This div should not touch the other div.</div>
</body>
</html>
最佳答案
您已正确识别问题。 float <div>
不再用于计算上边距,因此 2 <div>
只是互相对接。解决这个问题的一个简单方法就是包装第二个 <div>
.这将允许包装器(无形地)与第一个 <div>
对接。 , 并允许您为其指定空格。
让包装器正常工作的诀窍是让空白区域成为内部空白区域。换句话说,包装器使用填充而不是边距。这意味着包装器外部发生的任何事情(就像其他 float 元素一样)都无关紧要。
<div style="float: left; border: solid red 1px">foo</div>
<div class="wrapper" style="clear: both; padding-top: 90px;">
<div style="border: solid red 1px">This div should not touch the other div.</div>
</div>
关于html - 为什么在 float 元素之后忽略 html 元素的上边距?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1883414/