3

OK, I'm really having problems understanding the behavior of the float property.

The page is 750 px wide. In order to keep it positioned in the center of the screen, I used this code:

<div align="center">
    <div align="left" style="width:750px; border-style:double;">
        stuff
    </div>
</div>

The elements within the main 750 px wide container are other containers that have the following styles:

div.infoCont //these containers usualy have two more containers within- for an image and text
{
    width: 740px;
    position: relative;
    left: 2px;
    border-style: double; //for debugging
    float: left;
}
div.textContNI //text only
{
    width: 730px;
    float: left;
    clear: right;
    border-style: double; //for debugging
}

The small containers behave normally (they should be, because they are positioned and as big as the way I want to). But the height of the main container is A LOT less that the total height of the smaller containers... 0 px. It ignores the height of ALL the smaller containers.

This can be "fixed" by adding text right before the closing tag of the main container. I can also manipulate the height with <br> tags and no text: the height becomes as big as the total height of the borders. Another way to "fix" the problem is to add float:left; in the style, but that positions the container on the left side of the window and I can't have that.

I'm missing something and I don't know what it is.

Why does the main container ignore the total height of the containers within it and how can I take care of this bug?

4

1 回答 1

9

包含浮动元素

这是浮动元素的正确行为。这不是一个错误。

默认情况下,浮动元素不占用其父元素内的空间。给定绝对位置的元素也会发生同样的情况。父母有两个孩子,但他们都是浮动的,所以没有任何东西占用父母的空间。结果,父级的高度为零,除非它包含其他一些非浮动内容。

有三种常见的方法可以使父级包含其浮动的子级,以使其至少与其子级一样高。

1.固定高度

给父母一个固定的高度,至少与浮动孩子的高度一样高。从技术上讲,浮动元素仍然不占用父元素内的空间,但父元素足够高,使其看起来好像确实如此。

.parent { height: 30px; }
.child  { height: 30px; float: left; }

2.清除div

clear:both在父级内部添加一个尾随 div 。这会强制父级包含浮动的子级。父级会根据需要自动增加高度。默认情况下,空 div 在所有浏览器中的高度为零,因此尾随 div 不需要额外的样式。

.clear { clear: both; }
...
<div class="parent">
    <!-- Floated children go here -->
    ...
    <!-- Trailing clear div goes here -->
    <div class="clear"></div>
</div>

3.清除修复

将 clearfix 规则添加到 CSS 样式表,并将类添加clearfix到父级。最终结果与添加一个清晰的 div 相同,但不需要添加额外的 HTML 元素。就像添加一个清晰的 div 一样,这会强制父级包含浮动的子级。父级会根据需要自动增加高度。

/* The traditional version of clearfix, a good one to start with. */
.clearfix:after {
    content: ".";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden;
}
.clearfix {display: inline-block;}
* html .clearfix {height: 1%;}
.clearfix {display: block;}
...
<div class="parent clearfix">
    <!-- Floated children go here -->
    ...
</div>
于 2013-04-03T12:32:21.330 回答