如何让圆形关闭按钮内mark div的文本实现水平垂直居中
方案1:现有代码最小改动
你当前的.mark已经完全撑满父按钮容器,只需要补充文本居中规则即可:
.close-button .mark { position: absolute; width: 100%; height: 100%; margin: 0; top: 0; left: 0; right: 0; bottom: 0; /* 新增规则 */ text-align: center; line-height: 5em; }
line-height取值和按钮高度保持一致即可实现单行文本垂直居中,适合不需要后续修改按钮尺寸的场景。
方案2:自适应flex实现(推荐)
不需要绑定按钮固定高度,后续修改按钮尺寸无需同步调整居中规则:
.close-button .mark { position: absolute; width: 100%; height: 100%; margin: 0; top: 0; left: 0; right: 0; bottom: 0; /* 新增规则 */ display: flex; align-items: center; justify-content: center; }
方案3:冗余代码优化方案
其实不需要给.mark添加绝对定位,直接在父级按钮上做居中处理即可,代码更简洁:
.close-button { margin-top: auto; padding: 0; cursor: pointer; border: none; border-radius: 5rem; background: black; color: white; position: relative; width: 5em; height: 5em; /* 新增规则,直接在父容器完成居中 */ display: flex; align-items: center; justify-content: center; } .close-button .mark { margin: 0; }
<button class="close-button"> <div class="mark">+</div> </button>
内容的提问来源于stack exchange,提问作者matrixmarten
相关产品推荐
相关产品推荐

