清除:两者都不起作用 css 浮动
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18025818/
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
clear:both not working css floats
提问by Dude
Im not sure why my float isn't clearing so that a child container will stay inside the parent container.
我不知道为什么我的浮点数没有清除,所以子容器将留在父容器内。
Have a look at this jsfiddleto see what i mean. I want the .shadow-wrapper
div to encompass all the other elements that follow it. How can I get the parent container to encompass the child elements?
看看这个 jsfiddle看看我的意思。我希望.shadow-wrapper
div 包含它后面的所有其他元素。如何让父容器包含子元素?
回答by user1721135
Use this:
用这个:
.shadow-wrapper {
background-color: red;
clear: both;
overflow:hidden;
}
To enclose floated elements you can use any the following:
要包含浮动元素,您可以使用以下任何内容:
float:left;
overflow:hidden;
display:table;
display:inline-block;
display:table-cell;
Other solution using the :after method:
使用 :after 方法的其他解决方案:
.shadow-wrapper:after {
clear:both;
content:" ";
display:block;
}
As you can see from this codes, clear both doesnt need to be applied everywhere, only after the last element which is floated, and therefore we can use the after method which simulates this.
从这段代码中可以看出,clear both 不需要在任何地方都应用,只在最后一个浮动的元素之后,因此我们可以使用 after 方法来模拟它。
回答by Chris Bier
One option is to add float:left;
to .shadow-wrapper
.
一种选择是添加float:left;
到.shadow-wrapper
.
.shadow-wrapper {
background-color: red;
clear: both;
float: left;
}
回答by callmehiphop
A general rule for using floats and clears is that if you float one item, you should probably float all of its siblings too. If that seems problematic, you can add an extra div as the last childand clear both with that div, that should fix your issue.
使用浮动和清除的一般规则是,如果你浮动一个项目,你可能也应该浮动它的所有兄弟。如果这看起来有问题,您可以添加一个额外的 div 作为最后一个孩子,并使用该 div 清除两者,这应该可以解决您的问题。
<div class="wrapper">
<div class="floating-thing">Hellllllooooo</div>
<div class="non-floating-thing">Weeeeeeee</div>
<div class="clearfix"></div>
</div>