CSS弹窗字数统计文本无法居中的问题求助
CSS居中失效问题:字数统计文本无法在弹窗容器内居中
开发文本编辑器时,希望将.pop容器内的span文本(字数统计)居中显示,但文本始终处于边缘位置。以下是相关代码:
CSS代码
@import url("https://fonts.googleapis.com/css?family=Montserrat:400,400i,700"); body { font-family: Montserrat, sans-serif; } h1{ -webkit-user-select: none; -ms-user-select: none; user-select: none; text-align : center; } article { text-align : justify; overflow:auto; line-height: 1.5; height : 70vh; margin : auto; font-family: Montserrat, sans-serif; outline : none; width : 85%; } .outer { display : flex; } .pops { padding : 0px 15px; } .pop span { text-align:center; font-size : 20px; color : #444; text-align: center; } .pop{ transition: .5s; width: 120px; height : 70px; border-radius: 5px; border: 1px solid #BFBFBF; background-color: white; } .pop:hover { background-color : #eae8ff; }
HTML代码
<h1> StreamLine </h1> <div class = "outer"> <article class = "child" id = "text" data-gramm="false" data-gramm_editor="false" data-enable-grammarly="false" contenteditable = "true" spellcheck = "true"> Write your amazing words here! </article> <div class = "pops" > <div class = "pop"> <span class = "inner" id="words">0</span></div></div> </div>
问题原因
<span>是行内元素,text-align:center仅对块级元素生效,即使设置该属性,span也不会占满.pop容器宽度,无法实现水平居中。.pop容器未设置垂直居中的布局规则,文本默认对齐容器顶部。
解决方法
最简洁通用的方式是给.pop容器添加flex布局,实现水平+垂直双居中:
修改.pop的CSS代码:
.pop{ transition: .5s; width: 120px; height : 70px; border-radius: 5px; border: 1px solid #BFBFBF; background-color: white; /* 添加以下三行 */ display: flex; justify-content: center; /* 水平居中 */ align-items: center; /* 垂直居中 */ }
同时可删除.pop span中重复的text-align:center,flex布局已能实现居中效果,无需额外设置。
若不想使用flex,也可用grid布局替代:
.pop{ /* 替换flex相关代码为 */ display: grid; place-items: center; /* 同时实现水平和垂直居中 */ }
内容的提问来源于stack exchange,提问作者user21717124
相关产品推荐
相关产品推荐

