首页 > 开发 > CSS > 正文

浅谈CSS 高度塌陷问题

2024-07-11 08:31:30
字体:
来源:转载
供稿:网友

表现

例如:

HTML:

<div class="first"> <div class="first-child1">first-child1</div> <div class="first-child2">first-child2</div></div><div class="second"> second</div><div class="third"> third</div>

CSS:

.first{ width: 300px; background-color: pink;}.first .first-child1,.first .first-child2{ float: left; width: 100px; height: 100px;}.first .first-child1{ background-color: purple; margin-right: 10px;}.first .first-child2{ background-color: red; }.second{ width: 200px; height: 150px; background-color: blue;}.third{ width: 100px; height: 150px; background-color: green;}

表现为:

产生的原因

由上面的例子可以看出,first盒子没有设置高度,由子元素撑开,但是由于子盒子设置了浮动,脱离了标准流,所以导致first盒子没有高度,表现为second和third盒子向上移动了。

可以得出产生高度塌陷的原因:

在文档流中,父元素的高度默认是被子元素撑开的,也就是子元素多高,父元素就多高。但是当为子元素设置浮动以后,子元素会完全脱离文档流,此时将会导致子元素无法撑起父元素的高度,导致父元素的高度塌陷。由于父元素的高度塌陷了,则父元素下的所有元素都会向上移动,这样将会导致页面布局混乱。

高度塌陷的解决办法:

1、给父元素设置固定高度。但是使用这种方式后,父元素的高度就不能根据子元素自动撑高了,可以根据自己页面的特点,如果可以固定高度,可以使用这种方式,否则,不推荐这种方式。

2、额外标签法,这是w3c推荐的解决方案,但是不推荐,因为html的原则是写出语义化的标签,这种方式会额外增加无意义的标签。

<div class="first"> <div class="first-child1">first-child1</div> <div class="first-child2">first-child2</div> <div style="clear: both;"></div></div>

3、父元素的overflow属性(开启元素的BFC):

.clearfix{ overflow: hidden;}

使用这种方式,属性值可以是非visible(hidden/auto/scroll)中任意,但是建议用hidden。

这种方式副作用较小,这种方式在ie6中不支持,可以外加zoom: 1;

.clearfix::after{ content: "";/*伪元素内容为空*/ display: block;/*非默认的就行,也可以是table等等*/ height: 0;/*伪元素高度为0,不影响其他元素*/ clear: both;/*清除浮动*/ visibility: hidden;/*不可见*/}.clearfix{ zoom: 1;/*ie6元素没有BFC模式,但是这句代码会开启ie6中的hasLayout模式,只在ie中支持*/}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表