css父元素高度塌陷的几种情况

2,042 阅读2分钟

做题遇到一个题是关于造成父容器高度塌陷的,于是整理一下,以便回顾。

dispaly: inline

float

position: absolute

position: fixed

会造成父元素高度塌陷

dispaly: inline

若想使块级元素变成行内元素,就可以使用display: inline, 如果没有给父元素设置高度,父元素会随子元素塌陷,高度和子元素行高保持一致,

给父元素设定固定高度,则会保持原有高度

css:

.test-wrap {

  /* height: 200px;

  width: 200px; */

  border: solid 2px green;

  background-color: yellow;

}

.test-inline {

  height: 200px;

  width: 200px;

  border: solid 2px red;

  display: inline;

}

html:

<div class="test-wrap">

  <div class="test-inline">test!!!!!!</div>

</div>

float

float 属性定义元素在哪个方向浮动,float: left=>浮动在左侧, float: right=》浮动在右侧,float: none=>不浮动。不管原本是什么元素,float会使其生成一个块级框。

子元素使用浮动后会“漂浮”页面,不占用空间,如果父元素没有设置高度,则父元素高度变成零。

1.给父元素设置 overflow 属性可以清除浮动。将会使用父元素产生 BFC(block fomarttimg context) 机制,即父元素的高度计算会包括浮动元素的高度。

css:

.test-wrap {

  /* height: 200px;

  width: 200px; */

  border: solid 2px green;

  background-color: yellow;

  overflow: hidden;

}

.test-inline {

  height: 200px;

  width: 200px;

  border: solid 2px red;

  float: left;

}

2.通过::after伪元素清除对父元素浮动影响

css:

.test-wrap {   

  border: solid 2px green;

  background-color: yellow;

}

test-wrap::after {

  content: "";

  display: block;

  clear: both;

}

.test-inline {

  height: 200px;

  width: 200px;

  border: solid 2px red;

  float: left;

}

3.给父元素设定固定高度=》不够灵活

position: absolute

绝对定位不受文档流影响。如果父元素没有设置position,默认为position:static,此时父元素高度会塌陷。

  1. 给父元素设置position: relative\fixed\sticky(则子元素会相对于父元素定位), 再给父元素设置固定高度和宽度(可以通过JS获取子元素的高度document.getElementById("child").offsetHeight,然后赋值给父元素来解决。)

css:

.test-wrap {
  height: 200px;

  width: 200px;

  border: solid 2px green;

  background-color: yellow;

  overflow: hidden;

  position: fixed;

}

.test-inline {

  height: 200px;

  width: 200px;

  border: solid 2px red;

  position: absolute;

}

position: fixed

固定于页面某个位置。如果没有给父元素设置高度,父元素会随子元素塌陷,给父元素设置高度即可。

首发于移动云开发社区:ecloud.10086.cn/api/query/d…

参考文章:

doc.houdunren.com/css/8%20%E6…

blog.csdn.net/weixin_4406…