You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现自定义段落元素文本对齐?CSS居中失效问题排查

问题原因

自定义的<p1>和<p2>属于非标准HTML元素,浏览器默认将其渲染为行内(inline)元素,而text-align属性仅对块级元素生效——它控制的是块级元素内部内容的对齐,行内元素没有足够的宽度空间来实现居中效果。

而颜色、字体样式能生效,是因为这些属于继承属性,行内元素可以直接应用或继承这些样式。

解决方案

方案1:将自定义元素设为块级元素

在CSS中给<p1>和<p2>添加display: block;,让它们拥有块级元素的特性(默认占满父容器宽度),text-align即可生效:

body {
  background-color: floralwhite;
}

h1 {
  color: black;
  font-family: Calibri;
  font-size: 300%;
  text-align: center;
}

p1 {
  display: block; /* 添加这行 */
  text-align: center;
  color: lightseagreen;
  font-family: Calibri;
  font-size: 120%;
}

p2 {
  display: block; /* 添加这行 */
  text-align: center;
  color: deeppink;
  font-family: Calibri;
  font-size: 120%;
}

方案2:用class代替自定义元素(更符合HTML规范)

非标准自定义元素兼容性和可读性较差,推荐使用标准<p>元素配合class区分样式:

修改后的HTML

<h1> Header 1 </h1>
<br/>
<center>
  <iframe width="420" height="315" src="https://www.youtube.com/embed/FOXJdP7O6jg">
        </iframe>
</center>
<br/>
<br/>
<p class="p1"><b>This text should be bold </b>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to
  make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.</p>
<br/>
<br/>
<p class="p2"><b>This is Paragraph two we wil look</b></p>

对应的CSS

body {
  background-color: floralwhite;
}

h1 {
  color: black;
  font-family: Calibri;
  font-size: 300%;
  text-align: center;
}

.p1 {
  text-align: center;
  color: lightseagreen;
  font-family: Calibri;
  font-size: 120%;
}

.p2 {
  text-align: center;
  color: deeppink;
  font-family: Calibri;
  font-size: 120%;
}

内容的提问来源于stack exchange,提问作者Barney Collins

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 06:05:55