为什么浮动元素后html元素的顶部边距被忽略? [英] Why top margin of html element is ignored after floated element?

查看:106
本文介绍了为什么浮动元素后html元素的顶部边距被忽略?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个含2个div的页面。第一个是浮动的。第二个有一个clear:bothCSS声明和一个大的上边距。但是,当我在Firefox或IE8中查看页面时,我没有看到顶部边距。它看起来像第二个div接触第一个div,而不是分开。有没有办法使顶边距正常工作?

I have a page with 2 divs. The first one is floated. The 2nd one has a "clear: both" CSS declaration and a big top margin. However, when I view the page in Firefox or IE8, I don't see the top margin. It looks like the 2nd div is touching the first div, instead of being separated. Is there any way to make the top margin work properly?

我已经阅读CSS规范,注意到它说由于浮点不在流中,在浮动框之前和之后创建的定位块框垂直地流动,好像浮动不存在一样。

I have read the CSS spec and noticed that it says "Since a float is not in the flow, non-positioned block boxes created before and after the float box flow vertically as if the float didn't exist.". However, I don't know what to do about that.

这里是一个例子:

<!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>


推荐答案

浮动的< div> 不再用于计算上边距,因此2 < div> 只是互相对抗。一个简单的方法来解决这个问题只是为了包装第二个< div> 。这将允许包装器(不可见)与第一个< div> 对接,并允许你为它指定空格。

You've correctly identified the problem. The floated <div> is no longer used to calculate the top margin, and therefor the 2 <div>'s just butt against each other. A simple way to solve this is just to wrap the 2nd <div>. This will allow the wrapper to (invisibly) butt up against the first <div>, and allow you to specify white space for it.

使包装器正常工作的诀窍是让空白区域成为内部空白区域。换句话说,包装器使用填充而不是边距。这意味着包装器之外的任何事情(像其他浮动元素一样)并不重要。

The trick to getting the wrapper to work right is to have the white space be internal white space. In other words, the wrapper uses padding instead of margin. This means whatever is going on outside the wrapper (like other floating elements) won't really matter.

<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元素的顶部边距被忽略?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆