Div is not as tall as the total height of its floated children

前端 未结 1 734
心在旅途
心在旅途 2021-01-20 03:10

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

相关标签:
1条回答
  • 2021-01-20 04:02

    Containing floated elements

    This is the correct behavior of floated elements. It's not a bug.

    By default, a floated element doesn't occupy space within its parent. The same happens with elements given absolute position. The parent has two children, but they're both floated, so nothing occupies space in the parent. As a result the parent has a height of zero, unless it contains some other non-floated content.

    There are three common ways to make a parent contain its floated children, so that it's at least as tall as its children.

    1. Fixed height

    Give the parent a fixed height that's at least as tall as the height of the floated child. Technically, the floated element still does not occupy space within the parent, but the parent is tall enough to make it appear as if it does.

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

    2. clear div

    Add a trailing div with clear:both inside the parent. This forces the parent to contain the floated children. The parent automatically increases in height as needed. By default, an empty div has a height of zero in all browsers, so no additional styling is required for the trailing div.

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

    3. clearfix

    Add a clearfix rule to the CSS stylesheet, and add the class clearfix to the parent. The end result is the same as adding a clear div, but it doesn't require adding additional HTML elements. Like adding a clear div, this forces the parent to contain the floated children. The parent automatically increases in height as needed.

    /* 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>
    
    0 讨论(0)
提交回复
热议问题