【问题标题】:Need H2 to be only as wide as the text, but also text-align:center需要 H2 与文本一样宽,但也需要 text-align:center
【发布时间】:2016-05-21 12:08:30
【问题描述】:

我有两列,每列顶部都有 H2 标签。 H2 标签中的文本很短。标签具有蓝色背景。这是问题的一部分,因为作为普通的内联元素,蓝色背景将跨越 div 列的宽度。将H2 更改为display:inline-block 将解决此问题,但这会带来另一个问题,即text-align:center 不再有效,然后H2 标记将左对齐。

如何让 H2 元素的宽度与文本居中对齐?

<div style="width:auto;margin-left:auto;margin-right:auto;">
<h2 style="display:inline-block;background-color:#558ED5;color:#FFF;text-align:center;font-size:1.1em;padding:5px 10px 5px 10px;margin-left:auto;margin-right:auto;">WE OFFER 2 CLEANING OPTIONS:</h2>
</div>

【问题讨论】:

  • 如果不显示更多的 HTML,理想情况下是两个“列”、两个标题和限制这些列宽度的 CSS 的示例,就无法可靠地回答这个问题。请:显示足够的 ("minimal reproducible example") 代码,以便我们重现您的问题。

标签: html css


【解决方案1】:

添加文本对齐:居中;到主分区。像这样:

<div style="width:auto;margin-left:auto;margin-right:auto; text-align:center">
    <h2 style="display:inline-block;background-color:#558ED5;color:#FFF;text-align:center;font-size:1.1em;padding:5px 10px 5px 10px;margin-left:auto;margin-right:auto;">WE OFFER 2 CLEANING OPTIONS:</h2>
</div>

【讨论】:

  • BINGO!,它有效。将在 9 分钟内检查为正确答案,谢谢。
【解决方案2】:

您应该将容器 div 更改为 text-align:center 这将使具有 display:inline-block 的 h2 居中

<div style="width:auto;margin-left:auto;margin-right:auto;text-align:center">
<h2 style="display:inline-block;background-color:#558ED5;color:#FFF;text-align:center;font-size:1.1em;padding:5px 10px 5px 10px;margin-left:auto;margin-right:auto;">WE OFFER 2 CLEANING OPTIONS:</h2>
</div>

【讨论】:

  • 看起来很棒!谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-18
  • 2020-09-07
  • 2016-01-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多