div用了float浮动之后父元素div自动适应高度

转载自:http://hi.baidu.com/going5/item/f37dbe3eb7657b637d034b52

方法一:

html:

 

<div id="all1">

<div id="left1">1</div>

<div id="left2">1</div>

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

</div>

css:

 

#left1{ float:left;width:200px;}

#left2{ float:left;width:200px;}

#all1{}

这个方法的关键在于用了clear:both来清除了浮动元素,把父元素all1撑开。

方法二:html:

<div class="aa">

  <div class="bb">sffsssssssssssss</div>

  <div class="cc">sffss</div>

</div>

css:

 

.aa{ border:1px solid #000; background:#CC4;overflow:hidden;}

.bb { border:1px solid #f00; background:#999; float:left;}

.cc{ border:1px solid #f00; background:#999; float:left;}

此方法的重点在于,子元素有float之后,父元素需要设置一个overflow:hidden;,这样就可以自动撑开父元素aa。

 

总结如上的方法,各有适合的地方。比如overflow:hidden之后,超出父元素位置的子元素就看不到了,可以试一下如下的两段代码对比一下,

代码一:

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>无标题文档</title>

</head>

<style type="text/css" >

.aa{ border:1px solid #000; background:#CC4;overflow:hidden;}

.bb { border:1px solid #f00; background:#999; float:left; margin-top:-10px;margin-left:110px;}

.cc{ border:1px solid #f00; background:#999; float:left;}

</style>

<body>

<div class="aa">

  <div class="bb">图片</div>

  <div class="cc">图片</div>

</div>

</body>

</html>

 

代码二:

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>无标题文档</title>

</head>

<style type="text/css" >

.aa{ border:1px solid #000; background:#CC4;}

.bb { border:1px solid #f00; background:#999; float:left; margin-top:-10px;margin-left:110px;}

.cc{ border:1px solid #f00; background:#999; float:left;}

</style>

<body>

<div class="aa">

  <div class="bb">图片</div>

  <div class="cc">图片</div>

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

</div>

</body>

</html>

标签: none

添加新评论