子级float而父级div没高度的解决方法

问题:子级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>

 

 

 

转载于:https://www.cnblogs.com/super-zhen/p/3521073.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值