Floating elements within a div, floats outside of div. Why?

Say you have a div, say you color it green and give it a definite width, when I put stuff within it, in my case an img and another div. The idea is that the content of the container div will cause the container div to stretch out, and be a background for the contents. But when I do this, the containing div shrinks to fit the non-floating objects, and the floating objects will be either all the way out, or half out, half in, and not have any bearing on the size of the big div.

Why is this? Is there something I'm missing, and how can I get floated items to stretch out the height of a containing div?


The easiest is to put overflow:hidden on the parent div and don't specify a height:

#parent { overflow: hidden }

Another way is to also float the parent div:

#parent { float: left; width: 100% }

Another way uses a clear element:

<div class="parent">
   <img class="floated_child" src="..." />
   <span class="clear"></span>
</div>

CSS

span.clear { clear: left; display: block; }

Reason

The problem is that floating elements are out-of-flow:

An element is called out of flow if it is floated, absolutely positioned, or is the root element.

Therefore, they don't impact surrounding elements as an in-flow element would.

This is explained in 9.5 Floats:

Since a float is not in the flow, non-positioned block boxes created before and after the float box flow vertically as if the float did not exist. However, the current and subsequent line boxes created next to the float are shortened as necessary to make room for the margin box of the float.

html {
  width: 550px;
  border: 1px solid;
}
body {
  font-family: sans-serif;
  color: rgba(0,0,0,.15);
}
body:after {
  content: '';
  display: block;
  clear: both;
}
div {
  position: relative;
}
div:after {
  font-size: 200%;
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  text-align: center;
}
.block-sibling {
  border: 3px solid green;
}
.block-sibling:after {
  content: 'Block sibling';
  color: green;
}
.float {
  float: left;
  border: 3px solid red;
  height: 90px;
  width: 150px;
  z-index: 1;
}
.float:after {
  content: 'Float';
  color: red;
}
<div class="float"></div>
<div class="block-sibling">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur. Donec ut libero sed arcu vehicula ultricies a non tortor.
</div>

Put your floating div(s) in a div and in CSS give it overflow:hidden;
it will work fine.

链接地址: http://www.djcxy.com/p/7172.html

上一篇: 为什么Vim用〜扩展名保存文件?

下一篇: div内的浮动元素浮动在div之外。 为什么?