height:auto;当子元素使用float:left;or时如何获取父元素float:right?
父母
#parent {
width:100px;
height:auto;
padding-bottom:10px;
background:#0F0;
}
Run Code Online (Sandbox Code Playgroud)
child_left
#child_left {
width:50%;
height:50px;
float:left;
background:#00F;
}
Run Code Online (Sandbox Code Playgroud)
小提琴:http : //jsfiddle.net/27EWw/
元素的默认高度是auto,但您似乎在寻找 clearfix。如果一个元素的子元素是浮动的,它们本质上是从文档流中取出的,因此如果父元素没有定义的尺寸,它会自行折叠。您可以添加overflow:auto到父元素:
#parent {
width:100px;
overflow:auto;
padding-bottom:10px;
background:#0F0;
}
Run Code Online (Sandbox Code Playgroud)
或者,您也可以使用 clearfix:
#parent:after {
clear:both;
display:table;
content:'';
}
Run Code Online (Sandbox Code Playgroud)
你也可以有一个 clearfix 类,任何一个选项都可以。如果您想避免这些选项,您只需首先在父元素上设置尺寸。显然,这并不总是最好的选择,因为有些元素会有不同维度的子元素。