简体   繁体   English

为什么我的浮动元素不在其父元素内

[英]How come my float elements aren't within their parent

So basically i have this wrapper div, and all the elements inside it are floated elements. 所以基本上我有这个包装div,它里面的所有元素都是浮动元素。 Only thing is the border of the wrapper div does not include the floated elements in it. 唯一的问题是包装器div的边框不包含浮动元素。 Example: 例:

<div id = "wrapper>
   <div id = "content"></div>
</div>

heres the css: 继承人css:

#wrapper
{
   width:         1000px;
   margin-left:   auto;
   margin-right:  auto;
   border:        1px solid;
} 

#content
{
   border:        1px solid;
   width:         850px;
   height:        400px;
   display:       block;
   float:         left;
}

Basically #content is not enclosed within #wrapper's border, but still aligns within it, why is this? 基本上#content不包含在#wrapper的边框内,但仍然在其中对齐,为什么会这样?

You need to "clearfix" the container div. 你需要“清除”容器div。

Floated elements are not considered when calculating the dimensions of a container, however there are several workarounds to get what you want. 在计算容器的尺寸时不考虑浮动元素,但是有几种解决方法可以获得您想要的东西。

The Simplest 最简单的

Just add a div like this one as the last child in your container div: 只需添加像这样的div作为容器div中的最后一个子节点:

<div style="clear:both"></div>

As @Pekka comments there are many other ways to achieve the effect (without extra markup) listed in this SO question: 正如@Pekka评论,在这个SO问题中列出了许多其他方法来实现效果(没有额外的标记):

What methods of 'clearfix' can I use? 我可以使用哪种'clearfix'方法?

Because the point of float is to allow you to do things like 因为浮点数是允许你做的事情

图像跨越多个段落

Ed Eliot describes a large collection of different ways to make a container expand to contain it's floating children . 埃德艾略特描述了大量不同的方法,使容器扩展,以包含它的漂浮儿童 I generally recommend setting overflow: hidden on it (to establish a new block formatting context). 我通常建议设置overflow: hidden在它上面(建立一个新的块格式化上下文)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM