HTML高度塌陷

在正常的文档流中,夫元素的高度是被子元素撑开的

若子元素浮动,脱离文档流,会导致我们父元素高度丢失,这种情况我们叫高度塌陷

会影响页面布局,必须要解决

解决方案一:

给父元素设置固定高度,但在实际开发过程中,高度都是被内容撑开

.box1{border: 10px solid red;}

.box2{width: 200px; height: 200px; background-color: green; float: left; }

.box3{ height: 200px; width: 100%; background-color: yellow;}

<div class="box1">
        <div class="box2"></div>
    </div>
 <div class="box3"></div>

解决方案二:

页面中元素有隐含的属性,block formatting context 即块格式化上下文,简称bfc

当开启了bfc 后,元素会变成一个独立的布局,会有以下特带点

1:父元素的垂直外边距不会和子元素重叠

2:开启bfc的元素不会被浮动元素所覆盖

3:开启bfc的元素可以包含浮动的子元素(可以解决高度塌陷)

.box1{
       border: 10px solid red;
       float: left; */
       display: inline-block; */
       overflow: hidden;
       } 
 .box2{
       width: 200px;
       height: 200px;
       background-color: green;
       float: left;
       }
             
.box3{
        height: 200px;
        width: 100%;
        background-color: yellow;
      } 

如何开启bfc

1:设置·元素浮动

  不推荐,还是会改变页面的布局,而且父元素的宽度会丢失

2:设置元素inline-block

   不推荐,会丢失父元素的高度

3:将元素的overflow设置为一个非visble

   可以使用,也会产生一些小的副作用

4:设置元素的绝对定位

.box4{
       height: 200px;
       width:200px;
       background-color:gray;
       overflow: hidden;    }
.box5{
                 height: 100px;
                 width: 100px;
                 background-color:red;
             }
              .box6{
                 height: 100px;
                 width: 100px;
                 background-color:brown;
             }

由于受到浮动的影响,.box3,希望清除其他元素浮动对当前元素产生的影响

可以用clear属性完成

可选值:

nome  默认值  不清除浮动

left  清除左侧浮动元素对当前元素的影响

right  清除右侧浮动元素对当前元素的影响

both  清除两侧浮动元素对当前元素的影响

         清除对其他影响最大的那个元素的浮动

clear原理

 设置浮动后,浏览器会自动为元素添加上一个外边距,以示位置不受其他影响

.box1{
                 width: 200px;
                 height: 200px;
                 border: 10px solid red;
                 float: left;
                
             }
.box2{
                 width: 100px;
                 height: 100px;
                 background-color: green;
                 float:right;
             }
.box3{
                 height:300px;
                 width: 300px;
                 background-color: yellow;
                 clear: both;
                 
             }

<div class="box1"></div>
<div class="box2"></div>   
<div class="box3"></div>

解决方案三

利用clear:both;清除浮动

.box{   clear: both;  }

解决方案思:

在父元素后面加一个空的内容

利用clear:both;清除浮动影响

.box1:after{ 
              content: "";
              clear: both;
              display: block;
           }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值