Html 如果容器元素包含浮动元素,为什么它的高度不会增加?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16568272/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 08:24:34  来源:igfitidea点击:

Why doesn't the height of a container element increase if it contains floated elements?

htmlcsscss-float

提问by Boy Pasmo

I would like to ask how height and float work. I have an outer div and an inner div that has content in it. Its height may vary depending on the content of the inner div but it seems that my inner div will overflow its outside div. What would be the proper way to do it?

我想问一下高度和浮动是如何工作的。我有一个外部 div 和一个包含内容的内部 div。它的高度可能会因内部 div 的内容而异,但似乎我的内部 div 会溢出其外部 div。什么是正确的方法呢?

 <html>
    <body>
        <div style="margin:0 auto;width: 960px; min-height: 100px; background-color:orange">
         <div style="width:500px; height:200px; background-color:black; float:right"></div>
        </div>
    </body>
</html>

回答by Mr. Alien

The floated elements do not add to the height of the container element, and hence if you don't clear them, container height won't increase...

浮动元素不会增加容器元素的高度,因此如果不清除它们,容器高度不会增加......

I'll show you visually:

我将直观地向您展示:

enter image description here

在此处输入图片说明

enter image description here

在此处输入图片说明

enter image description here

在此处输入图片说明

More Explanation:

更多解释:

<div>
  <div style="float: left;"></div>
  <div style="width: 15px;"></div> <!-- This will shift 
                                        besides the top div. Why? Because of the top div 
                                        is floated left, making the 
                                        rest of the space blank -->

  <div style="clear: both;"></div> 
  <!-- Now in order to prevent the next div from floating beside the top ones, 
       we use `clear: both;`. This is like a wall, so now none of the div's 
       will be floated after this point. The container height will now also include the 
       height of these floated divs -->
  <div></div>
</div>

You can also add overflow: hidden;on container elements, but I would suggest you use clear: both;instead.

您也可以添加overflow: hidden;容器元素,但我建议您clear: both;改用。

Also if you might like to self-clear an element you can use

此外,如果您可能想自行清除可以使用的元素

.self_clear:after {
  content: "";
  clear: both;
  display: table;
}


How Does CSS Float Work?

CSS 浮动是如何工作的?

What is float exactly and what does it do?

什么是浮动,它有什么作用?

  • The floatproperty is misunderstood by most beginners. Well, what exactly does floatdo? Initially, the floatproperty was introduced to flow text around images, which are floated leftor right. Here's another explanationby @Madara Uchicha.

    So, is it wrong to use the floatproperty for placing boxes side by side? The answer is no; there is no problem if you use the floatproperty in order to set boxes side by side.

  • Floating an inlineor blocklevel element will make the element behave like an inline-blockelement.

    Demo

  • If you float an element leftor right, the widthof the element will be limited to the content it holds, unless widthis defined explicitly ...

  • You cannot floatan element center. This is the biggest issue I've always seen with beginners, using float: center;, which is not a valid value for the floatproperty. floatis generally used to float/move content to the very leftor to the very right. There are only fourvalid values for floatproperty i.e left, right, none(default) and inherit.

  • Parent element collapses, when it contains floated child elements, in order to prevent this, we use clear: both;property, to clear the floated elements on both the sides, which will prevent the collapsing of the parent element. For more information, you can refer my another answer here.

  • (Important)Think of it where we have a stack of various elements. When we use float: left;or float: right;the element moves above the stack by one. Hence the elements in the normal document flow will hide behind the floated elements because it is on stack level above the normal floated elements. (Please don't relate this to z-indexas that is completely different.)

  • float大多数初学者都误解了该属性。那么,究竟是做float什么的?最初,该float属性被引入以在图像周围流动文本,这些图像是浮动的leftright. 这是@Madara Uchicha的另一种解释

    那么,使用float属性来并排放置盒子是错误的吗?答案是否定的;如果您使用该float属性来并排设置框,则没有问题。

  • 浮动inlineblock级别元素将使元素表现得像一个inline-block元素。

    演示

  • 如果您浮动元素leftor right,则width元素的 将仅限于它所拥有的内容,除非width明确定义...

  • 你不能float是一个元素center。这是我在初学者中一直看到的最大问题,使用float: center;,这不是float属性的有效值。float通常用于float/move 内容到最左边或最右边。属性只有四个有效值,floatleftrightnone(默认)和inherit

  • 父元素折叠,当它包含浮动的子元素时,为了防止这种情况,我们使用clear: both;属性,清除两侧的浮动元素,这将防止父元素折叠。有关更多信息,您可以在此处参考我的另一个答案。

  • (重要)想想我们有一堆不同的元素。当我们使用float: left;orfloat: right;元素在堆栈上方移动一个。因此,普通文档流中的元素将隐藏在浮动元素后面,因为它位于普通浮动元素之上的堆栈级别。(请不要将其与此联系起来,z-index因为那是完全不同的。)



Taking a case as an example to explain how CSS floats work, assuming we need a simple 2 column layout with a header, footer, and 2 columns, so here is what the blueprint looks like...

以一个案例为例来解释CSS浮动是如何工作的,假设我们需要一个简单的2列布局,有一个页眉、页脚和2列,那么这里是蓝图的样子……

enter image description here

在此处输入图片说明

In the above example, we will be floating only the red boxes, either you can floatboth to the left, or you can floaton to left, and another to rightas well, depends on the layout, if it's 3 columns, you may float2 columns to leftwhere another one to the rightso depends, though in this example, we have a simplified 2 column layout so will floatone to leftand the other to the right.

在上面的例子中,我们将浮动只有红色箱子,要么你可以float同时向left,或者你可以floatleft,另一个right为好,取决于布局,如果是3列,你可能float2列left,其中另一一个到rightso取决于,尽管在这个例子中,我们有一个简化的2列布局,所以float一个到left另一个到right.

Markup and styles for creating the layout explained further down...

用于创建布局的标记和样式进一步解释...

<div class="main_wrap">
    <header>Header</header>
    <div class="wrapper clear">
        <div class="floated_left">
            This<br />
            is<br />
            just<br />
            a<br />
            left<br />
            floated<br />
            column<br />
        </div>
        <div class="floated_right">
            This<br />
            is<br />
            just<br />
            a<br />
            right<br />
            floated<br />
            column<br />
        </div>
    </div>
    <footer>Footer</footer>
</div>

* {
    -moz-box-sizing: border-box;       /* Just for demo purpose */
    -webkkit-box-sizing: border-box;   /* Just for demo purpose */
    box-sizing: border-box;            /* Just for demo purpose */
    margin: 0;
    padding: 0;
}

.main_wrap {
    margin: 20px;
    border: 3px solid black;
    width: 520px;
}

header, footer {
    height: 50px;
    border: 3px solid silver;
    text-align: center;
    line-height: 50px;
}

.wrapper {
    border: 3px solid green;
}

.floated_left {
    float: left;
    width: 200px;
    border: 3px solid red;
}

.floated_right {
    float: right;
    width: 300px;
    border: 3px solid red;
}

.clear:after {
    clear: both;
    content: "";
    display: table;
}

Let's go step by step with the layout and see how float works..

让我们一步一步地进行布局,看看浮动是如何工作的。

First of all, we use the main wrapper element, you can just assume that it's your viewport, then we use headerand assign a heightof 50pxso nothing fancy there. It's just a normal non floated block level element which will take up 100%horizontal space unless it's floated or we assign inline-blockto it.

首先,我们使用主包装元素,你可以假设它是你的视口,然后我们使用header并分配 a heightof 50pxso 没什么特别的。它只是一个普通的非浮动块级元素,它将占用100%水平空间,除非它是浮动的或我们分配inline-block给它的。

The first valid value for floatis leftso in our example, we use float: left;for .floated_left, so we intend to float a block to the leftof our container element.

在我们的示例中,for 的第一个有效值floatleft这样,我们使用float: left;for .floated_left,因此我们打算将块浮动到left容器元素的 。

Column floated to the left

列向左浮动

And yes, if you see, the parent element, which is .wrapperis collapsed, the one you see with a green border didn't expand, but it should right? Will come back to that in a while, for now, we have got a column floated to left.

是的,如果您看到.wrapper已折叠的父元素,您看到的带有绿色边框的父元素没有展开,但应该正确吗?稍后会回到那个,现在,我们有一个列浮动到left

Coming to the second column, lets it floatthis one to the right

来到第二列,让它float成为right

Another column floated to the right

另一列向右浮动

Here, we have a 300pxwide column which we floatto the right, which will sit beside the first column as it's floated to the left, and since it's floated to the left, it created empty gutter to the right, and since there was ample of space on the right, our rightfloated element sat perfectly beside the leftone.

在这里,我们有一个300px很宽的柱子,我们floatright,它会坐在第一列旁边,因为它漂浮到left,因为它漂浮到left,它为 创造了空的排水沟right,因为有足够的空间right,我们的right浮动元素完美地坐在旁边left

Still, the parent element is collapsed, well, let's fix that now. There are many ways to prevent the parent element from getting collapsed.

尽管如此,父元素还是折叠了,好吧,让我们现在解决这个问题。有很多方法可以防止父元素折叠。

  • Add an empty block level element and use clear: both;before the parent element ends, which holds floated elements, now this one is a cheap solution to clearyour floating elements which will do the job for you but, I would recommend not to use this.
  • 添加一个空的块级元素并clear: both;在父元素结束之前使用它,它包含浮动元素,现在这是clear浮动元素的廉价解决方案,它将为您完成这项工作,但我建议不要使用它。

Add, <div style="clear: both;"></div>before the .wrapperdivends, like

<div style="clear: both;"></div>.wrapperdiv结尾之前添加,例如

<div class="wrapper clear">
    <!-- Floated columns -->
    <div style="clear: both;"></div>
</div>

Demo

演示

Well, that fixes very well, no collapsed parent anymore, but it adds unnecessary markup to the DOM, so some suggest, to use overflow: hidden;on the parent element holding floated child elements which work as intended.

嗯,这修复得很好,不再有折叠的父级,但它向 DOM 添加了不必要的标记,所以有人建议,overflow: hidden;在父元素上使用浮动子元素,这些子元素按预期工作。

Use overflow: hidden;on .wrapper

使用overflow: hidden;.wrapper

.wrapper {
    border: 3px solid green;
    overflow: hidden;
}

Demo

演示

That saves us an element every time we need to clearfloatbut as I tested various cases with this, it failed in one particular one, which uses box-shadowon the child elements.

每次我们需要时,这都为我们节省了一个元素,clearfloat但是当我用它测试了各种情况时,它在一个特定的情况下失败了,它box-shadow在子元素上使用。

Demo(Can't see the shadow on all 4 sides, overflow: hidden;causes this issue)

Demo(4边都看不到阴影,overflow: hidden;导致这个问题)

So what now? Save an element, no overflow: hidden;so go for a clear fix hack, use the below snippet in your CSS, and just as you use overflow: hidden;for the parent element, call the classbelow on the parent element to self-clear.

所以现在怎么办?保存一个元素,不要overflow: hidden;那么做一个明确的修复黑客,在你的 CSS 中使用下面的代码片段,就像你overflow: hidden;用于父元素一样,在父元素上调用class下面的代码来自我清除。

.clear:after {
    clear: both;
    content: "";
    display: table;
}

<div class="wrapper clear">
    <!-- Floated Elements -->
</div>

Demo

演示

Here, shadow works as intended, also, it self-clears the parent element which prevents to collapse.

在这里,阴影按预期工作,而且它会自动清除防止折叠的父元素。

And lastly, we use footer after we clearthe floated elements.

最后,我们clear在浮动元素之后使用页脚。

Demo

演示



When is float: none;used anyways, as it is the default, so any use to declare float: none;?

什么时候float: none;使用,因为它是默认值,所以有什么用声明float: none;

Well, it depends, if you are going for a responsive design, you will use this value a lot of times, when you want your floated elements to render one below another at a certain resolution. For that float: none;property plays an important role there.

好吧,这取决于,如果您要进行响应式设计,当您希望浮动元素以特定分辨率呈现在另一个下方时,您将多次使用此值。因为该float: none;财产在那里起着重要作用。



Few real-world examples of how floatis useful.

很少有真实世界的例子说明如何float有用。

  • The first example we already saw is to create one or more than one column layouts.
  • Using imgfloated inside pwhich will enable our content to flow around.
  • 我们已经看到的第一个示例是创建一个或多个列布局。
  • 使用imgfloat insidep这将使我们的内容能够四处流动。

Demo(Without floating img)

演示(无浮动img

Demo 2(imgfloated to the left)

演示 2(img浮动到left)

  • Using floatfor creating horizontal menu - Demo
  • 使用float用于创建水平菜单-演示


Float second element as well, or use `margin`

也浮动第二个元素,或使用 `margin`

Last but not the least, I want to explain this particular case where you floatonly single element to the leftbut you do not floatthe other, so what happens?

最后但并非最不重要的一点是,我想解释这种特殊情况,即您float只将单个元素添加到 中,left而您没有添加float到另一个元素,那么会发生什么?

Suppose if we remove float: right;from our .floated_rightclass, the divwill be rendered from extreme leftas it isn't floated.

假设如果我们float: right;从我们的 中移除.floated_rightclassdiv将会从extreme 渲染,left因为它不是浮动的。

Demo

演示

So in this case, either you can floatthe to the leftas well

所以在这种情况下,要么你float将到left,以及

OR

或者

You can use margin-leftwhich will be equal to the size of the left floated column i.e 200pxwide.

您可以使用margin-leftwhich 将等于左浮动列的大小,即200px

回答by j08691

You need to add overflow:autoto your parent div for it to encompass the inner floated div:

您需要添加overflow:auto到您的父 div 以包含内部浮动 div:

<div style="margin:0 auto;width: 960px; min-height: 100px; background-color:orange;overflow:auto">
    <div style="width:500px; height:200px; background-color:black; float:right">
    </div>
</div>

jsFiddle example

jsFiddle 示例

回答by Maloric

You are encountering the float bug (though I'm not sure if it's technically a bug due to how many browsers exhibit this behaviour). Here is what is happening:

您遇到了浮动错误(尽管由于有多少浏览器表现出这种行为,我不确定它在技术上是否是错误)。这是正在发生的事情:

Under normal circumstances, assuming that no explicit height has been set, a block level element such as a div will set its height based on its content. The bottom of the parent div will extend beyond the last element. Unfortunately, floating an element stops the parent from taking the floated element into account when determining its height. This means that if your last element is floated, it will not "stretch" the parent in the same way a normal element would.

一般情况下,假设没有设置明确的高度,div等块级元素会根据其内容来设置高度。父 div 的底部将超出最后一个元素。不幸的是,浮动元素会阻止父元素在确定其高度时考虑浮动元素。这意味着如果你的最后一个元素是浮动的,它不会像普通元素那样“拉伸”父元素。

Clearing

清算

There are two common ways to fix this. The first is to add a "clearing" element; that is, another element below the floated one that will force the parent to stretch. So add the following html as the last child:

有两种常见的方法可以解决这个问题。首先是添加一个“清算”元素;也就是说,浮动元素下方的另一个元素将迫使父元素拉伸。所以添加以下 html 作为最后一个孩子:

<div style="clear:both"></div>

It shouldn't be visible, and by using clear:both, you make sure that it won't sit next to the floated element, but after it.

它不应该是可见的,并且通过使用 clear:both,您可以确保它不会位于浮动元素旁边,而是位于它之后。

Overflow:

溢出:

The second method, which is preferred by most people (I think) is to change the CSS of the parent element so that the overflow is anything but "visible". So setting the overflow to "hidden" will force the parent to stretch beyond the bottom of the floated child. This is only true if you haven't set a height on the parent, of course.

大多数人(我认为)首选的第二种方法是更改​​父元素的 CSS,这样溢出就不会“可见”。因此,将溢出设置为“隐藏”将迫使父级超出浮动子级的底部。当然,这仅在您尚未为父级设置高度时才适用。

Like I said, the second method is preferred as it doesn't require you to go and add semantically meaningless elements to your markup, but there are times when you need the overflowto be visible, in which case adding a clearing element is more than acceptable.

就像我说的,第二种方法是首选,因为它不需要你去添加语义无意义的元素到你的标记,但有时你需要overflow可见,在这种情况下添加清除元素是可以接受的.

回答by Alejandro Ruiz Arias

You confuse how browsers renders the elements when there are floating elements. If one block element is floating (your inner div in your case), other block elements will ignore it because browser removes floating elements from the normal flow of the web page. Then, because the floated div has been removed from the normal flow, the outside div is filled in, like the inner div isn't there. However, inline elements (images, links, text, blackquotes) will respect the boundaries of the floating element. If you introduce text in the outside div, the text will place arround de inner div.

当有浮动元素时,您会混淆浏览器如何呈现元素。如果一个块元素是浮动的(在您的情况下是您的内部 div),其他块元素将忽略它,因为浏览器会从网页的正常流程中删除浮动元素。然后,因为浮动 div 已从正常流中移除,所以外部 div 被填充,就像内部 div 不在那里一样。但是,内联元素(图像、链接、文本、黑色引号)将遵守浮动元素的边界。如果在外部 div 中引入文本,则文本将放置在内部 div 的周围。

In other words, block elements (headers, paragraphs, divs, etc) ignore floating elements and fill in, and inline elements (images, links, text, etc) respect boundaries of floating elements.

换句话说,块元素(标题、段落、div 等)忽略浮动元素并填充,而内联元素(图像、链接、文本等)尊重浮动元素的边界。

An fiddle example here

这里有一个小提琴示例

<body>
    <div style="float:right; background-color:blue;width:200px;min-height:400px;margin-right:20px">
           floating element
    </div>
    <h1 style="background-color:red;"> this is a big header</h1>
    <p style="background-color:green"> this is a parragraph with text and a big image. The text places arrounds the floating element. Because of the image is wider than space between paragrah and floating element places down the floating element. Try to make wider the viewport and see what happens :D
        <img src="http://2.bp.blogspot.com/_nKxzQGcCLtQ/TBYPAJ6xM4I/AAAAAAAAAC8/lG6XemOXosU/s1600/css.png">
     </p>

回答by Starx

Its because of the float of the div. Add overflow: hiddenon the outside element.

这是因为 div 的浮动。添加overflow: hidden外部元素。

<div style="overflow:hidden; margin:0 auto;width: 960px; min-height: 100px; background-color:orange;">
    <div style="width:500px; height:200px; background-color:black; float:right">
    </div>
</div>

Demo

演示

回答by Yusufbek

Try this one

试试这个

.parent_div{
    display: flex;
}

回答by Nishant Rana

you can use overflow property to the container div if you don't have any div to show over the container eg:

如果没有任何 div 显示在容器上,则可以对容器 div 使用溢出属性,例如:

<div class="cointainer">
    <div class="one">Content One</div>
    <div class="two">Content Two</div>
</div>

Here is the following css:

这是以下css:

.container{
    width:100%;/* As per your requirment */
    height:auto;
    float:left;
    overflow:hidden;
}
.one{
    width:200px;/* As per your requirment */
    height:auto;
    float:left;
}

.two{
    width:200px;/* As per your requirment */
    height:auto;
    float:left;
}

-----------------------OR------------------------------

- - - - - - - - - - - -或者 - - - - - - - - - - - - - ----

    <div class="cointainer">
        <div class="one">Content One</div>
        <div class="two">Content Two</div>
        <div class="clearfix"></div>
    </div>

Here is the following css:

这是以下css:

    .container{
        width:100%;/* As per your requirment */
        height:auto;
        float:left;
        overflow:hidden;
    }
    .one{
        width:200px;/* As per your requirment */
        height:auto;
        float:left;
    }

    .two{
        width:200px;/* As per your requirment */
        height:auto;
        float:left;
    }
    .clearfix:before,
    .clearfix:after{
        display: table;
        content: " ";
    }
    .clearfix:after{
        clear: both;
    }