CSS 高度塌陷 Height crash

本文探讨了CSS中元素浮动导致的父元素高度坍塌问题,并提供了多种解决方案,包括使用BFC、固定高度、伪元素清除浮动等,适用于不同场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

See original article https://dyingdown.github.io/2020/04/09/Height-crash/

Environment: When you set float to an element, and it’s parent’s width or height follows the element’s width or height. Then, the parent will lose its width or height and it’s called height crash. Here are some solutions.

Fixed height

Set the height of the parent to a fixed number. This will work but, when the child element changed, the parent element won’t change. So this solutions works but a good one.

BFC

According to the Standard of W3C, every element in the page has a hidden attribute called BFC, short for Block Formatting Context. This attribute is off by default.

Attributes when BFS is on

  1. Vertical margin of parent item won’t overlap with child item
  2. BFC-on element won’t be covered by float element
  3. BFC-on element can contain float child element

How to open BFC

  1. Set float to parent item

    This way will make the parent item lose its width, and following item will still move

  2. Set absolute position for parent item

    The same as the first one

  3. Set inline-block for item

    Also lose width

  4. Set the value of overflow to a non-visible value

    This works!

Overflow

overflow: hidden;
overflow: auto;

If there is a relative positioned item in the parent element and the item is out of the range, you won’t be able to see it.

In IE6 or lower, the browser doesn’t support BFC, it has an attribute call hasLayout, familiar to BFC.

Zoom (IE6)

/* IE6 */
zoom: 1;

Zoom means enlarge the element. Value 1 means the element is the same size as before.

Use this way to enable hasLayout.

Set width

Set width to a certain value for the parent element.

Blank element

  1. Add a blank div at the bottom of the parent element. Clear float of the blank div.

Since this element is not float, the parent height will be stretched.

Basically has no side effect.

	<style>
    .clear {
        clear: both;
    }
</style>
<div class="box1">
    <div class="box2"></div>
    <div class="clear"></div>
</div>

However, this will add redundant struct in page. So this is not recommended.

  1. Add a Pseudo Class :after
.clearfix:after {
    /* add content */
    content: "";
    /* change into a block element */
    display: block;
    /* clear float on both side */
    clear: both;
}
<div class="box1 clearfix">
    <div class="box2"></div>
</div>

In IE6, :after is not supported, so we still need zoom.

.clearfix {
    zoom: 1;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值