如何在Bootstrap的thead表头中实现文本与caret箭头垂直居中对齐
Bootstrap表头文本与caret插入符垂直对齐解决方案
问题背景
使用Bootstrap开发HTML表格时,thead区域的列标题文本与右侧caret插入符出现明显错位:"Title"文本位置偏高,右侧caret箭头位置偏低,需要实现二者在表头区域内垂直居中对齐。
原始代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Table Test</title> <link rel="stylesheet" href="css/all.css" /> <link rel="stylesheet" href="css/bootstrap.min.css" /> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" /> </head> <body> <div class="container"> <div> <table class="table table-dark table-striped table-hover table-bordered"> <thead class="thead-dark"> <tr> <th scope="col"> Title <div style="float: right; display: inline;"> <div style="height: 16px"> <i class="fas fa-caret-up" style="height: fit-content; vertical-align: bottom; font-size: 20px;"></i> </div> <div style="height: 16px;"> <i class="fas fa-caret-down" style="height: fit-content; vertical-align: top; font-size: 20px;"></i> </div> </div> </th> <th scope="col">Foo</th> <th scope="col">Bar</th> <th scope="col">Quax</th> </tr> </thead> <tbody> <tr> </tr> </tbody> </table> </div> </div> </body> </html>
错误效果

修复方案
错位是由于float浮动布局与嵌套固定高度div的写法导致的对齐偏差,改用Bootstrap内置的flex布局工具类即可快速解决,无需额外写复杂内联样式:
- 给
<th>标签添加d-flex align-items-center justify-content-between三个工具类,自动实现内部元素垂直居中、两端对齐 - 右侧箭头容器改用flex列布局,去掉所有浮动、固定高度相关的内联样式
修改后的<th>代码如下:
<th scope="col" class="d-flex align-items-center justify-content-between"> Title <div class="d-flex flex-column"> <i class="fas fa-caret-up" style="font-size: 20px;"></i> <i class="fas fa-caret-down" style="font-size: 20px; margin-top: -4px;"></i> </div> </th>
如果需要调整箭头间距,可调整下箭头的margin-top负边距数值,适配不同字体大小的对齐效果。
内容的提问来源于stack exchange,提问作者Stuart
相关产品推荐
相关产品推荐

