在现代网页设计中,CSS(层叠样式表)是不可或缺的一部分。在过去,使用position: absolute定位元素是一种常见的技术,但是随着前端开发的发展,现代CSS系统倾向于减少或避免使用absolute定位。本文将探讨这一趋势的原因,并提供一些示例代码以说明替代方法。
这里我们先举一个关于脱离文档流的bug例子,是我们项目中真实遇到的一个bug。
示例代码:
html
<div class="container"> <div class="bigbox"> <div class="box"> <label class="label-selected">Collapsed All</label> <div class="button-box"> <button>switch</button> </div> <label class="label-selected">Expanded All</label> </div> </div> </div>
css
<style> .container { height: 400px; overflow: scroll; } .bigbox { height: 800px; } .box { display: flex; line-height: 25px; align-items: center; margin-top: 10px; } .label-selected { font-weight: 600; font-size: 14px; line-height: 20px; margin: 0 10px; } .button-box { margin: 0 8px; } </style>
首先先看下正常的一个样式,三个元素依次居中排列,随着鼠标滚动而滚动