[ HTML/CSS ] 设置元素浮动之后父元素的高度为 0

其实这个我也就是照搬的,一共五种方法设置(下面的代码是 html 代码):

1 <div class= "container">
2     <div class="left"></div>
3     <div class="right"></div>
4 </div>

方法一:BFC(块级格式化上下文)

 1 .container{
 2     width:1000px;height:400px;border: 1px solid red;
 3 }
 4 .left{
 5     width:200px;height:100%;background: gray;
 6     float: left;
 7 }
 8 .right{
 9     overflow:hidden;  /* 触发bfc */
10     background: green;
11 }

方法二:flex 弹性布局

 1 .container{
 2     width:1000px;height:400px;border:1px solid red;
 3     display:flex;         /*flex布局*/
 4 }
 5 .left{
 6     width:200px; height:100%;background:gray;
 7     flex:none;
 8 }
 9 .right{
10     height:100%;background:green;
11     flex:1;        /*flex布局*/
12 }

方法三:css计算宽度 calc

 1 .container{
 2     width:1000px;height:400px;border:1px solid red;
 3 }
 4 .left{
 5     width:200px;height:100%;background:gray;
 6     float:left;
 7 }
 8 .right{
 9     height:100%;background:green;
10     float:right;
11     width:calc(100% - 200px);
12 }

方法四:table布局

 1 .container{
 2     width:1000px;height:400px;border:1px solid red;
 3     display:table;         /*table布局*/
 4 }
 5 .left{
 6     width:200px; height:100%;background:gray;
 7     display:table-cell;
 8 }
 9 .right{
10     height:100%;background:green;
11     display: table-cell;
12 }

方法五:为右边元素设置margin-left

1 .container{
2     width:1000px;height:400px;border:1px solid red;
3 }
4 .left{
5     float:left;width:200px;border:1px solid red;height:100%;background:gray;
6 }
7 .right{
8     height:100%;border:1px solid blue;width:auto;margin-left:200px;
9 }

注释:在不同的环境请斟酌使用上述布局

博主水平有限,难免疏漏有误,欢迎交流指正。
博客为作者原创,版权所有,保留一切权利。仅供学习和参考,转载必须注明博主ID和转载链接。
原文地址:https://www.cnblogs.com/ExileRiven/p/13191097.html