div包含多個position:absolute的span,清除浮動後div高度為0,未被撐開。
絕對定位元素完全脫離標準文檔流:
position:relative)僅提供定位基準,不包裹絕對定位子元素。.test { height: 100px; } /* 或 min-height */
.test { display: flex; justify-content: space-between; }
span { position: static; } /* 取消absolute */
const container = document.querySelector('.test');
const spans = container.querySelectorAll('span');
let maxBottom = 0;
spans.forEach(s => {
const rect = s.getBoundingClientRect();
maxBottom = Math.max(maxBottom, rect.bottom);
});
container.style.height = (maxBottom - container.getBoundingClientRect().top) + 'px';
.test::after { content: ''; display: block; height: 1px; }
| 特性 | float | position:absolute |
|---|---|---|
| 文檔流 | 半脫離(文字環繞) | 完全脫離 |
| 父容器高度 | 塌陷,可clearfix恢復 | 塌陷,clearfix無效 |
| 定位基準 | 正常流位置 | 最近非static祖先 |
| 典型用途 | 多欄布局、文字環繞 | 彈窗、Tooltip、固定UI |