使用Bootstrap框架时无法实现多个元素同行显示问题求助
解决方案
核心问题出在你外层容器用了Bootstrap的d-grid类,该类会将容器设置为单列网格布局,所有子元素默认独占一行,所以你给子元素设置inline-block不会生效——网格布局的子元素display属性会被覆盖为grid-item,自然不会按行内块排列。
直接修改容器的类即可实现你要的效果:
把 <div class="d-grid gap-2 col-6 mx-auto"> 替换为 <div class="d-flex flex-wrap align-items-center gap-2 col-6 mx-auto">
d-flex开启弹性布局,默认子元素横向排列align-items-center让所有行内元素垂直居中对齐,避免图片和文字高度不一致错位flex-wrap保证空间不足时元素可以自动换行,不会溢出容器- 如果需要
<hr>分隔线单独占满整行,给<hr>加style="width: 100%; margin: 8px 0;"即可
完整可运行代码示例
<!-- Bootstrap --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet"> <style> h2 { color: Red; font-size: 30px; font-weight: bold; } img { display: inline-block; } h2.class1 { color: green; font-size: 20px; } h2.class2 { color: yellow; font-size: 14px; } .bg { background-color: black; } </style> <!-- Code --> <div class="bg"> <div class="container-sm center" style="margin-top: 25px;"> <div class="d-flex flex-wrap align-items-center gap-2 col-6 mx-auto"> <img src="https://via.placeholder.com/50" width="50px" height="50px" style="border-radius:25px;"> <h2 style="font-size: 25px;">Some Heading Text</h2> <h2 class="class1">{}</h2> <h2 class="class2"> Some Tagline Like Text</h2> <hr style="width: 100%; margin: 0.5rem 0;"> </div> </div> </div>
修改后就和你移除Bootstrap后的预期效果完全一致。
内容的提问来源于stack exchange,提问作者Blind Spot
相关产品推荐
相关产品推荐

