开发者

Floated element gets outside of its parent?

开发者 https://www.devze.com 2023-02-07 04:40 出处:网络
I have an left floated div in another div and the floated divs content is getting out of the parent. See live:

I have an left floated div in another div and the floated divs content is getting out of the parent.

See live:

http://jsfiddle.net/eWkUg/

* {
  margin: 0;
  padding: 0;
  list-style: none;
}
ul {
  width: 600px;
}
ul li {
  border: solid 1px #000;
  margin: 15px 0;
}
.img-section {
  float: left;
  border: solid 1px red;
}
<ul>
  <li>
    <div class="img-section">
      <img src="http://www.placehold.it/50X100">开发者_Python百科
    </div>
     Hello world
  </li>
  <li>
    How to avoid the red box getting out of the black one? (and hiding another list element)
  </li>
</ul>

I've been trying clear: left/right/both, but nothing helps.

How to avoid this? I HAVE to float the whole div (not the contents) due to image overlay (not included in example above)


You can fix it by adding overflow:auto to ul li, if I understand your problem correctly.


I am not sure if this is what you need, but you can add overflow:hidden for ul li this will show the image's div wrapped by the li.

Demo: http://jsfiddle.net/eWkUg/9/


Floated elements do not expand their parent's height. This causes the effect you see.

You must add a block-level element with clear: left; after the last floated element:

<li>
    <div class="img-section"><img /></div>
    <div class="text-section">...</div>
    <br style="clear: left;" />
</li>

Usually a <br> is used for that purpose.


Change the layout to:

<ul>
    <li>
       <div class="img-section">...</div>
       <div class="text-section">...</div>
       <br style="clear:left" /> <<---- add this 
    </li>
    etc...

Once you float an element, it's somewhat removed from the document flow, and you have to force the parent container to extend past the floated element's lower limit. You do that by adding that extra
line.


Add clear:both to ul li:

ul li {
    border: solid 1px #000;
    margin: 15px 0;
    clear:both;
}

http://jsfiddle.net/hAFWA/

0

精彩评论

暂无评论...
验证码 换一张
取 消