Html 你如何防止浮动元素的父元素崩溃?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/218760/
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-28 22:33:16  来源:igfitidea点击:

How do you keep parents of floated elements from collapsing?

htmlcsslayoutcss-floatclearfix

提问by Nathan Long

Although elements like <div>s normally grow to fit their contents, using the floatproperty can cause a startling problem for CSS newbies: If floated elements have non-floated parent elements, the parent will collapse.

尽管像<div>s这样的元素通常会随着它们的内容而增长,但使用该float属性可能会给CSS 新手带来一个令人吃惊的问题:如果浮动元素具有非浮动父元素,则父元素将崩溃。

For example:

例如:

<div>
  <div style="float: left;">Div 1</div>
  <div style="float: left;">Div 2</div>
</div>

The parent div in this example will not expandto contain its floated children - it will appear to have height: 0.

此示例中的父 div不会扩展以包含其浮动子项 - 它看起来具有height: 0.

How do you solve this problem?

你怎么解决这个问题?

I would like to create an exhaustive list of solutions here. If you're aware of cross-browser compatibility issues, please point them out.

我想在这里创建一个详尽的解决方案列表。如果您知道跨浏览器兼容性问题,请指出。

Solution 1

解决方案1

Float the parent.

浮动父级。

<div style="float: left;">
  <div style="float: left;">Div 1</div>
  <div style="float: left;">Div 2</div>
</div>

Pros: Semantic code.
Cons: You may not always want the parent floated. Even if you do, do you float the parents' parent, and so on? Must you float every ancestor element?

优点:语义代码。
缺点:您可能并不总是希望父浮动。即使你这样做,你是否浮动父母的父母,等等?你必须浮动每个祖先元素吗?

Solution 2

解决方案2

Give the parent an explicit height.

给父母一个明确的高度。

<div style="height: 300px;">
  <div style="float: left;">Div 1</div>
  <div style="float: left;">Div 2</div>
</div>

Pros: Semantic code.
Cons: Not flexible - if the content changes or the browser is resized, the layout will break.

优点:语义代码。
缺点:不灵活 - 如果内容更改或浏览器调整大小,布局将中断。

Solution 3

解决方案3

Append a "spacer" element inside the parent element, like this:

在父元素内附加一个“间隔”元素,如下所示:

<div>
  <div style="float: left;">Div 1</div>
  <div style="float: left;">Div 2</div>
  <div class="spacer" style="clear: both;"></div>
</div>

Pros: Straightforward to code.
Cons: Not semantic; the spacer div exists only as a layout hack.

优点:直接编码。
缺点:没有语义;间隔 div 仅作为布局技巧存在。

Solution 4

解决方案4

Set parent to overflow: auto.

将父设置为overflow: auto.

<div style="overflow: auto;">
  <div style="float: left;">Div 1</div>
  <div style="float: left;">Div 2</div>
</div>

Pros: Doesn't require extra div.
Cons: Seems like a hack - that's not the overflowproperty's stated purpose.

优点:不需要额外的 div。
缺点: 看起来像一个黑客 - 这不是overflow财产的既定目的。

Comments? Other suggestions?

注释?其他建议?

回答by A.M.K

Solution 1:

解决方案1:

The most reliable and unobtrusive method appears to be this:

最可靠和不引人注目的方法似乎是这样的:

Demo: http://jsfiddle.net/SO_AMK/wXaEH/

演示:http: //jsfiddle.net/SO_AMK/wXaEH/

HTML:

HTML:

<div class="clearfix">
    <div style="float: left;">Div 1</div>
    <div style="float: left;">Div 2</div>
</div>?

CSS:

CSS:

.clearfix::after { 
   content: " ";
   display: block; 
   height: 0; 
   clear: both;
}

?With a little CSS targeting, you don't even need to add a class to the parent DIV.

? 使用一点 CSS 定位,您甚至不需要向 parent 添加一个类DIV

This solution is backward compatible with IE8 so you don't need to worry about older browsers failing.

此解决方案与 IE8 向后兼容,因此您无需担心旧浏览器失败。

Solution 2:

解决方案2:

An adaptation of solution 1 has been suggested and is as follows:

已建议对解决方案 1 进行修改,如下所示:

Demo: http://jsfiddle.net/wXaEH/162/

演示:http: //jsfiddle.net/wXaEH/162/

HTML:

HTML:

<div class="clearfix">
    <div style="float: left;">Div 1</div>
    <div style="float: left;">Div 2</div>
</div>?

CSS:

CSS:

.clearfix::after { 
   content: " ";
   display: block; 
   height: 0; 
   clear: both;
   *zoom: expression( this.runtimeStyle['zoom'] = '1', this.innerHTML += '<div class="ie7-clear"></div>' );
}

.ie7-clear {
    display: block;
    clear: both;
}

This solution appears to be backward compatible to IE5.5 but is untested.

此解决方案似乎向后兼容 IE5.5,但未经测试。

Solution 3:

解决方案3:

It's also possible to set display: inline-block;and width: 100%;to emulate a normal block element while not collapsing.

也可以在不折叠的情况下设置display: inline-block;width: 100%;模拟普通块元素。

Demo: http://jsfiddle.net/SO_AMK/ae5ey/

演示:http: //jsfiddle.net/SO_AMK/ae5ey/

CSS:

CSS:

.clearfix {
    display: inline-block;
    width: 100%;
}

This solution should be backward compatible with IE5.5 but has only been tested in IE6.

该解决方案应该向后兼容 IE5.5,但仅在 IE6 中进行了测试。

回答by Bobby Hyman

I usually use the overflow: autotrick; although that's not, strictly speaking, the intended use for overflow, it iskinda related - enough to make it easy to remember, certainly. The meaning of float: leftitself has been extended for various uses more significantly than overflow is in this example, IMO.

我通常使用这个overflow: auto技巧;虽然这不是严格来说,溢出的用途,它有点关系-足以令它容易记住,一定。float: left本身的含义已经扩展到各种用途,比这个例子中的溢出更重要,IMO。

回答by tybro0103

Rather than putting overflow:autoon the parent, put overflow:hidden

而不是穿上overflow:auto父母,穿上overflow:hidden

The first CSS I write for any webpage is always:

我为任何网页编写的第一个 CSS 始终是:

div {
  overflow:hidden;
}

Then I never have to worry about it.

那我就再也不用担心了。

回答by Sarfraz

The problem happens when a floated element is within a container box, that element does not automatically force the container's height adjust to the floated element. When an element is floated, its parent no longer contains it because the float is removed from the flow. You can use 2 methods to fix it:

当浮动元素在容器框内时会出现问题,该元素不会自动强制容器的高度调整为浮动元素。当一个元素被浮动时,它的父元素不再包含它,因为浮动被从流中移除。您可以使用 2 种方法来修复它:

  • { clear: both; }
  • clearfix
  • { clear: both; }
  • clearfix

Once you understand what is happening, use the method below to “clearfix” it.

一旦您了解正在发生的事情,请使用以下方法“清除”它。

.clearfix:after {
    content: ".";
    display: block;
    clear: both;
    visibility: hidden;
    line-height: 0;
    height: 0;
}

.clearfix {
    display: inline-block;
}

html[xmlns] .clearfix {
    display: block;
}

* html .clearfix {
    height: 1%;
}

Demonstration :)

示范:)

回答by John Slegers

There are several versions of the clearfix, with Nicolas Gallagherand Thierry Koblentzas key authors.

clearfix 有多个版本,主要作者是Nicolas GallagherThierry Koblentz

If you want support for older browsers, it's best to use this clearfix :

如果你想支持旧浏览器,最好使用这个 clearfix :

.clearfix:before, .clearfix:after {
    content: "";
    display: table;
}

.clearfix:after {
    clear: both;
}

.clearfix {
    *zoom: 1;
}

In SCSS, you should use the following technique :

在 SCSS 中,您应该使用以下技术:

%clearfix {
  &:before, &:after {
    content:" ";
    display:table;
  }

  &:after {
    clear:both;
  }

  & {
    *zoom:1;
  }
}

#clearfixedelement {
    @extend %clearfix;
}

If you don't care about support for older browsers, there's a shorter version :

如果您不关心对旧浏览器的支持,还有一个较短的版本:

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

回答by lededje

Strange no one has come up with a complete answer for this yet, ah well here it is.

奇怪的是还没有人想出一个完整的答案,嗯,就是这样。

Solution one: clear: both

解决方案一:清除:两者

Adding a block element with the style clear:both; onto it will clear the floats past that point and stop the parent of that element from collapsing. http://jsfiddle.net/TVD2X/1/

添加一个样式为 clear:both 的块元素;到它上面将清除超过该点的浮点数并阻止该元素的父元素折叠。http://jsfiddle.net/TVD2X/1/

Pros: Allows you to clear an element and elements you add below will not be effected by the floated elements above and valid css.

优点:允许您清除元素,您在下方添加的元素不会受到上方浮动元素和有效 css 的影响。

Cons: Requires the another tag to clear the floats, bloating markup.

缺点:需要另一个标签来清除浮动、膨胀标记。

Note: To fall back to IE6 and for it to work on abstinent parents (i.e. the input element) you are not able to use :after.

注意:要回退到 IE6 并让它在禁欲的父母(即输入元素)上工作,您不能使用 :after。

Solution two: display: table

解决方案二:显示:表格

Adding display:table; to the parent to make it shrug off the floats and display with the correct height. http://jsfiddle.net/h9GAZ/1/

添加显示:表格;到父级,使其摆脱浮标并以正确的高度显示。http://jsfiddle.net/h9GAZ/1/

Pros: No extra markup and is a lot neater. Works in IE6+

优点:没有额外的标记,而且更整洁。适用于 IE6+

Cons: Requires invalid css to make sure everything plays nice in IE6 and 7.

缺点:需要无效的 css 以确保在 IE6 和 7 中一切正常。

Note: The IE6 and 7 width auto is used to prevent the width being 100%+padding, which is not the case in newer browsers.

注意:IE6 和 7 的宽度自动用于防止宽度为 100%+padding,在较新的浏览器中不是这种情况。

A note on the other "solutions"

关于其他“解决方案”的说明

These fixes work back to the lowest supported browser, over 1% usage globally (IE6), which means using :after does not cut it.

这些修复可以返回到最低支持的浏览器,全球使用率超过 1% (IE6),这意味着使用 :after 不会削减它。

Overflow hidden does show the content but does not prevent the element from collapsing and so does not answer the question. Using an inline block can have buggy results, children having strange margins and so on, table is much better.

溢出隐藏确实显示内容,但不会阻止元素折叠,因此不会回答问题。使用内联块可能会产生错误的结果,孩子有奇怪的边距等等,表格要好得多。

Setting the height does "prevent" the collapse but it is not a proper fix.

设置高度确实“防止”了坍塌,但这不是一个正确的解决方法。

Invalid css

无效的 CSS

Invalid css never hurt anyone, in fact, it is now the norm. Using browser prefixes is just as invalid as using browser specific hacks and doesn't impact the end user what so ever.

无效的 css 从来没有伤害过任何人,事实上,它现在是常态。使用浏览器前缀与使用浏览器特定的黑客一样无效,并且不会影响最终用户。

In conclusion

综上所述

I use both of the above solutions to make elements react correctly and play nicely with each other, I implore you to do the same.

我使用上述两种解决方案来使元素正确反应并相互配合,我恳请您也这样做。

回答by Bryan A

Although the code isn't perfectly semantic, I think it's more straightforward to have what I call a "clearing div" at the bottom of every container with floats in it. In fact, I've included the following style rule in my reset block for every project:

尽管代码不是完全语义化的,但我认为在每个带有浮点数的容器底部放置一个我称之为“清除 div”的东西更直接。事实上,我在每个项目的重置块中都包含了以下样式规则:

.clear 
{
   clear: both;
}

If you're styling for IE6 (god help you), you might want to give this rule a 0px line-height and height as well.

如果您正在为 IE6 设计样式(上帝帮助您),您可能还想为此规则设置 0px 行高和高度。

回答by DisgruntledGoat

The ideal solution would be to use inline-blockfor the columns instead of floating. I think the browser support is pretty good if you follow (a) apply inline-blockonly to elements that are normally inline (eg span); and (b) add -moz-inline-boxfor Firefox.

理想的解决方案是使用inline-block列而不是浮动。如果您遵循 (a)inline-block仅适用于通常内联的元素(例如span),我认为浏览器支持非常好;(b)-moz-inline-box为 Firefox添加。

Check your page in FF2 as well because I had a ton of problems when nesting certain elements (surprisingly, this is the one case where IE performs much better than FF).

也请在 FF2 中检查您的页面,因为我在嵌套某些元素时遇到了很多问题(令人惊讶的是,这是 IE 性能比 FF 好得多的一种情况)。

回答by Konrad Rudolph

I use 2 and 4 where applicable (i.e. when I know the content's height or if overflowing doesn't harm). Anywhere else, I go with solution 3. By the way, your first solution has no advantage over 3 (that I can spot) because it isn't any more semantic since it uses the same dummy element.

我在适用的情况下使用 2 和 4(即当我知道内容的高度或溢出不会造成伤害时)。在其他任何地方,我都使用解决方案 3。顺便说一句,您的第一个解决方案没有比 3(我可以发现的)优势,因为它不再具有语义,因为它使用相同的虚拟元素。

By the way, I wouldn't be concerned about the fourth solution being a hack. Hacks in CSS would only be harmful if their underlying behaviour is subject to reinterpretation or other change. This way, your hack wouldn't be guaranteed to work. However in this case, your hack relies on the exact behaviour that overflow: autois meant to have. No harm in hitching a free ride.

顺便说一句,我不会担心第四个解决方案是一个黑客。CSS 中的 Hack 只有在其潜在行为受到重新解释或其他更改时才会有害。这样,您的 hack 就不能保证有效。但是,在这种情况下,您的 hack 依赖于预期的确切行为overflow: auto。搭便车没有坏处。

回答by Christian Gray

My favourite method is using a clearfix class for parent element

我最喜欢的方法是为父元素使用 clearfix 类

.clearfix:after {
    content: ".";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden;
}

.clearfix {
    display: inline-block;
}

* html .clearfix {
    height: 1%;
}

.clearfix {
    display: block;
}