Bootstrap图标gear-fill未完全居中,求精准居中解决方案
解决Bootstrap齿轮图标在圆形容器中偏移的问题
方案一:调整容器布局,直接居中图标元素
将居中逻辑移到容器本身,避开字体图标自带的基线偏移干扰,这是最稳定的解决方式:
<span class="float-end btn-setting" on:click={modalMypage.show} on:keydown={modalMypage.show}> <i class="bi bi-gear-fill"></i> </span>
.btn-setting { width: 28px; height: 28px; border-radius: 50%; background-color: white; cursor: pointer; transition: background-color .2s ease; /* 容器直接设置flex居中 */ display: flex; align-items: center; justify-content: center; /* 解决hover时边框撑大容器的问题 */ box-sizing: border-box; } .btn-setting > i { font-size: 18px; color: #959FFF; } .btn-setting:hover { background-color: transparent; border: 1px solid white; } .btn-setting:hover > i { color: white; }
方案二:修正伪元素的字体对齐属性
如果坚持使用伪元素的实现方式,需要消除字体图标默认的基线偏移:
.btn-setting { width: 28px; height: 28px; border-radius: 50%; position: relative; background-color: white; cursor: pointer; transition: background-color .2s ease; /* 必须添加,避免hover边框改变容器尺寸 */ box-sizing: border-box; } .btn-setting > i:before { font-size: 18px; color: #959FFF; position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; /* 消除字体基线带来的偏移 */ line-height: 1; vertical-align: middle; } .btn-setting:hover { background-color: transparent; border: 1px solid white; } .btn-setting:hover > i::before { color: white; }
关键注意点
- 原代码hover时添加的
border:1px solid white会让容器尺寸从28px变为30px,必须加上box-sizing:border-box保证容器尺寸稳定,否则会间接影响视觉居中效果。 - Bootstrap图标本质是字体元素,部分图标存在细微的字体基线偏移,直接在容器上使用flex居中能避开这类字体属性干扰。
内容的提问来源于stack exchange,提问作者Yeol
相关产品推荐
相关产品推荐

