如何让HTML中Buy文本居中?text-align:center失效问题求助
解决「Buy」文本无法居中的问题
问题原因
你当前的代码里,「Buy」放在<span>标签中,而<span>是行内元素,它的宽度仅适配内容本身;同时包裹它的<p>标签没有设置text-align:center,所以无法让内部的行内元素居中。
两种可行解决方案
方案1:给包裹Buy的p标签添加居中类
直接复用你已有的.f类(该类已设置text-align:center),修改对应的HTML代码:
<p class="f"> <span class="buy">Buy</span> </p>
方案2:将Buy的span改为块级元素并居中
修改.buy的CSS样式,让它成为块级元素,再通过margin: 0 auto实现居中:
.buy { background-color: rgb(73, 73, 247); font-weight: bold; padding-left: 15px; padding-right: 15px; padding-top: 7px; padding-bottom: 7px; color: white; border-radius: 30px; /* 新增以下样式 */ display: block; width: fit-content; margin: 0 auto; }
修改后的完整代码示例(以方案1为例)
CSS代码
.buy { background-color: rgb(73, 73, 247); font-weight: bold; padding-left: 15px; padding-right: 15px; padding-top: 7px; padding-bottom: 7px; color: white; border-radius: 30px; } .f { text-align: center; margin-top: 0; margin-bottom: 0; } .pros { font-weight: bold; text-align: center; font-size: 42px; margin-top: 3px; margin-bottom: 15px; } .mac { text-align: center; font-weight: bold; font-size: 25px; margin-top: 5px; margin-bottom: 0; } .new { text-align: center; font-weight: bold; color: orangered; margin-bottom: 0; } .p { font-family: Arial; text-align: center; }
HTML代码
<p class="new"> New </p> <p class="mac"> MacBook Pro </p> <p class="pros"> Supercharged for pros. </p> <p class="f"> From $1999 </p> <p class="f"> <span class="buy">Buy</span> </p>
内容的提问来源于stack exchange,提问作者Mohamad
相关产品推荐
相关产品推荐

