Bootstrap 5实现Flex列子元素全宽等高布局的方法咨询
使用Bootstrap 5实现纵向均分布局

我希望左侧的元素纵向排列,每个元素宽度与父元素一致,高度均分并填满父元素的全部高度(实际会有3个及以上元素,此处用3个做测试)。使用最新版Bootstrap 5能否实现该效果?
现有代码
HTML代码
<div class="row come-in"> <div class="col-md-1 sections"> <div>All</div> <div>Best</div> <div>Ever</div> </div>....
CSS代码
.sections { text-orientation: upright; writing-mode:vertical-lr; align-items: stretch; flex-flow: column; } .sections > div { width: max-content; flex-grow: 1; }
当然可以用Bootstrap 5实现,直接用它的内置Flex布局类就能简化代码,同时满足需求:
优化后的实现方案
HTML结构
<div class="row come-in"> <div class="col-md-1 sections d-flex flex-column"> <div class="flex-fill d-flex align-items-center justify-content-center">All</div> <div class="flex-fill d-flex align-items-center justify-content-center">Best</div> <div class="flex-fill d-flex align-items-center justify-content-center">Ever</div> </div> <!-- 右侧其他列内容 --> </div>
简化后的CSS
.sections { text-orientation: upright; writing-mode: vertical-lr; }
关键说明
d-flex flex-column:给父容器.sections添加这两个Bootstrap类,直接实现纵向Flex布局,替代自定义的flex-flow: columnflex-fill:每个子元素加这个类,就能自动均分父容器的可用高度,完美替代flex-grow: 1- 去掉了原CSS里的
align-items: stretch和width: max-content——因为Bootstrap的Flex布局默认会让子元素拉伸填满父容器宽度,刚好符合你“宽度与父元素一致”的要求 align-items-center justify-content-center是可选的,用来让文字在每个子元素里居中显示,你可以根据需求调整或移除
这样既利用了Bootstrap的原生能力,又精准实现了你要的纵向排列、高度均分、宽度填充满父容器的效果,同时保留了垂直文字的显示方向。
内容的提问来源于stack exchange,提问作者Sasha
相关产品推荐
相关产品推荐

