首页 > 技术文章 > 子级float而父级div没高度的解决方法

super-zhen 2014-01-15 16:27 原文

问题:子级float而父级没有高度

有问题的代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>父div不自适应高度实例</title>
<style>
.divcss5 {
    width:500px;
    border:1px solid #000;
    padding:10px;
}
.divcss5-lf {
    float:left;
    width:220px;
    height:100px;
    background:#000
}
.divcss5-rt {
    float:right;
    width:230px;
    height:100px;
    background:#06F
}
</style>
</head>
<body>
<div class="divcss5">
  <div class="divcss5-lf"></div>
  <div class="divcss5-rt"></div>
</div>
</body>
</html>

 

方法A: 给父级设置固定高度

缺点:父级是固定高度,而不随内容高度自适应高度。此方法针对能确定父div内的内容高度情况下使用。

解决问题后代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>父div不自适应高度实例</title>
<style>
.divcss5 {
    width:500px;
    border:1px solid #000;
    padding:10px;
    height:100px;
}
.divcss5-lf {
    float:left;
    width:220px;
    height:100px;
    background:#000
}
.divcss5-rt {
    float:right;
    width:230px;
    height:100px;
    background:#06F
}
</style>
</head>
<body>
<div class="divcss5">
  <div class="divcss5-lf"></div>
  <div class="divcss5-rt"></div>
</div>
</body>
</html>

 

 

方法B: 使用css clear清除浮动

.clear {clear:both;}

<div class=”clear”></div>

注意:在父级</div>前加class为clear的div。

 解决问题后代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>父div不自适应高度实例</title>
<style>
.divcss5 {
    width:500px;
    border:1px solid #000;
    padding:10px;
}
.divcss5-lf {
    float:left;
    width:220px;
    height:100px;
    background:#000
}
.divcss5-rt {
    float:right;
    width:230px;
    height:100px;
    background:#06F
}
.clear {
    clear:both;
}
</style>
</head>
<body>
<div class="divcss5">
  <div class="divcss5-lf"></div>
  <div class="divcss5-rt"></div>
  <div class="clear"></div>
</div>
</body>
</html>

 

 

方法C: 对父级样式加overflow样式 【推荐此方法】

此方法不增加div盒子对象,只需要对父级加一个overflow:hidden样式即可。

解决问题后代码:

 

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>父div不自适应高度实例</title>
<style>
.divcss5 {
    width:500px;
    border:1px solid #000;
    padding:10px;
    overflow:hidden;
}
.divcss5-lf {
    float:left;
    width:220px;
    height:100px;
    background:#000
}
.divcss5-rt {
    float:right;
    width:230px;
    height:100px;
    background:#06F
}
</style>
</head>
<body>
<div class="divcss5">
  <div class="divcss5-lf"></div>
  <div class="divcss5-rt"></div>
</div>
</body>
</html>

 

 

 

推荐阅读