0

Why the <h1> tag with clear both is at the bottom, if get rid of "clear both", it works fine, how can I get it work with clear both?

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=gbk"/>
<style>
#left{
    float:left;
    width:200px;
    height:400px;
    background:#cfc;
}
#main{
    margin-left:210px;
    background:#f9c;
    height:400px;
}
h1{
    clear:both;
}
</style>
</head>
<body>
<div id="left"></div>
<div id="main">
    <h1>test</h1>
</div>
</body>
</html>
4

3 回答 3

2

The comment by Mr. Alien explains why your having your problem, and an easy way to fix it is to add the following code to your CSS, and remove the clear: both from your h1 properties:

#main:after {
    visibility: hidden;
    content: " ";
    clear: both;
    height: 0;

}

If you are going to go float crazy, it is easier to just create a clearfix class that you can apply to your elements. Here is a link that describes how to do exactly that.

于 2013-05-14T06:18:21.940 回答
1

Your questions:

1- Why the tag with clear both is at the bottom?

According to css specs for clear:

both
Requires that the top border edge of the box be below the bottom outer edge of any right-floating and left-floating boxes that resulted from elements earlier in the source document.

So the clear:both; on h1 also clears the float on an earlier element, which is not even part of the containing div of the h1.

2- How can I get it work with clear both?

If you need to keep clear:both; on h1 and keep it at the beginning of its container div, the simplest way is to add overflow:auto; to the container.

Demo

#main {
    margin-left:210px;
    background:#f9c;
    height:400px;
    overflow:auto;
}
于 2013-05-14T06:57:06.677 回答
0

It is working as it should work. The layout affected is the one of the H1. Not the layout of main. W3c says.. "The clear property indicates which sides of an element's box(es) may not be adjacent to an earlier floating box."

So your H1 is going down until it accomplish the constraint. It does not matter that H1 is a child of main div. It must accomplish the constraint as well.

enter image description here So if you (for any reason) need to apply clear both to your H1 and at the same time get to avoid the constrain related to your previous floating box, you must absolute position main . You will need a containing block as well so I added the div container relative positioned

You can see it working here in this fiddle

#container {
position:relative;
}
#left{
    float:left;
    width:200px;
    height:400px;
    background:#cfc;
}
#main{
    position:absolute;
    left:210px;
    right:0px;
    background:#f9c;
    height:400px;

}

h1{
    clear:both;    
}
于 2013-05-14T06:55:22.083 回答