div 内浮动元素,div 外浮动.为什么? [英] Floating elements within a div, floats outside of div. Why?

查看:48
本文介绍了div 内浮动元素,div 外浮动.为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设你有一个 div,给它一个明确的 width 并将元素放入其中,在我的例子中是一个 img 和另一个 div.

这个想法是容器div的内容会导致容器div向外伸展,成为内容的背景.但是当我这样做时,包含的 div 会缩小以适应非浮动对象,并且浮动对象将要么完全出来,要么一半出来,一半进去,并且与大 div 的大小.

这是为什么?有什么我遗漏的吗,我怎样才能让浮动项目伸展包含 divheight ?

解决方案

最简单的就是把overflow:hidden放在父div上,不指定高度:

#parent { 溢出:隐藏}

另一种方法是同时浮动父div:

#parent { float: left;宽度:100% }

另一种使用清晰元素的方法:

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

CSS

span.clear { clear: left;显示:块;}

Say you have a div, give it a definite width and put elements in 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 content. 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; }

这篇关于div 内浮动元素,div 外浮动.为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆