如何实现div内文本居中?下拉菜单h4调整尺寸文本置顶问题求解
问题原因
你设置的text-align: center仅能实现文本水平居中,出现文本置顶的核心原因是没有配置垂直居中规则,同时h4标签默认自带的上下外边距也会打乱排版。
修复方案
适配你现有代码逻辑的最简修改方案,仅需要更新.dropdown-content h4的CSS规则,新增3个属性即可:
.dropdown-content h4 { height: 35px; background-color: #fff; border: none; border-radius: 5px; color: #353535; transition: all 0.3s ease-in-out; display: none; /* 新增以下3行属性 */ margin: 0; /* 清除h4标签默认自带的上下外边距 */ text-align: center; /* 水平居中 */ line-height: 35px; /* 行高等于容器高度,实现单行文本垂直居中 */ }
扩展说明
如果后续下拉选项文本可能出现多行的情况,推荐改用flex布局实现更稳定的居中效果,修改规则如下:
- 更新
.dropdown-content h4的CSS属性:
.dropdown-content h4 { height: 35px; margin: 0; background-color: #fff; border: none; border-radius: 5px; color: #353535; transition: all 0.3s ease-in-out; display: none; /* 新增flex居中规则 */ align-items: center; /* 垂直居中 */ justify-content: center; /* 水平居中 */ }
- 同步修改
.show类的规则,保证显示逻辑正常:
.show {display: flex !important;}
内容的提问来源于stack exchange,提问作者JTsoc
相关产品推荐
相关产品推荐

