如何将flex父容器首个子元素排除在flex计算外并相对父级定位
完全不需要新增额外HTML结构,直接靠现有CSS属性就能实现需求。
实现原理
给flex子元素设置position: absolute后,该元素会自动脱离正常文档流,本身就不会参与flex布局的空间分配、对齐计算,完全满足你“排除在flex布局计算之外”的要求。你之前遇到定位跑到页面右上角的问题,只是因为flex父容器没有建立定位上下文,导致绝对定位的参考对象是整个视口而非父容器。
具体修改步骤
- 给flex父容器
.mycontainer添加position: relative,建立专属定位上下文,后续子元素的绝对定位就会以该父容器为参考边界 - 工具栏的定位规则按需调整即可:固定到右上角保留
top: 0; right: 0,固定到左上角就改成top: 0; left: 0 - (可选)如果担心工具栏遮挡下方正常排列的flex内容,给父容器对应方位加少量内边距预留空间即可,比如固定右上角就给父容器加
padding-top: 25px; padding-right: 25px
修正后完整代码
CSS部分:
.mycontainer{ background-color: rgb(200,200,200); width: 100%; display: flex; flex-direction: column; align-items: center; justify-content: space-between; /* 新增:建立定位上下文 */ position: relative; /* 可选:给工具栏预留位置,避免遮挡内容 */ padding: 25px 5px 5px 5px; } .mycontainer-bar{ width: 20px; height: 20px; background-color: red; position: absolute; /* 固定在父容器右上角 */ top: 0; right: 0; /* 要固定左上角就替换为下面两行 */ /* top: 0; left: 0; */ } .row{ margin: 5px; background-color: blue; width: 80%; height: 90px; }
HTML部分完全不需要改动,沿用你原来的结构即可:
<div class="mycontainer"> <div class="mycontainer-bar">t</div> <div class="row">r1</div> <div class="row">r2</div> </div>
内容的提问来源于stack exchange,提问作者Kora21
相关产品推荐
相关产品推荐

