How do I get a div to wrap around floating children?

怎甘沉沦 提交于 2019-12-21 04:27:10

问题


Considering the following code, where the span elements are floating inside of the div, how can I make the div wrap around the floating child elements, so that the 1px border wraps the children elements?

<div style="border:1px solid #000">
  <span style="float:left">Content</span>
  <span style="float:left">Content</span>
  <span style="float:left">Content</span>
</div>

回答1:


Most of the time, adding overflow:hidden on the wrapper is sufficient:

<div style="border:1px solid #000; overflow:hidden;">
    <span style="float:left">Content</span>
    <span style="float:left">Content</span>
    <span style="float:left">Content</span>
</div>

Sometimes, you'll see this alternate approach (which is much more hacky, but probably has better back-version browser support).

<div style="border:1px solid #000; ">
    <span style="float:left">Content</span>
    <span style="float:left">Content</span>
    <span style="float:left">Content</span>
    <div style="clear:both;"></div>
</div>



回答2:


Use the clear CSS property according to MDN web docs: https://developer.mozilla.org/en-US/docs/Web/CSS/clear

Note: If an element contains only floated elements, its height collapses to nothing. If you want it to always be able to resize, so that it contains floating elements inside it, you need to self-clear its children. This is called clearfix, and one way to do it is clear a replaced ::after pseudo-element on it.

#container::after { 
  content: "";
  display: block; 
  clear: both;
}


来源:https://stackoverflow.com/questions/4357981/how-do-i-get-a-div-to-wrap-around-floating-children

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!