将自动宽度应用于 H1 标题

Apply Auto Width to an H1 Heading

如何获得 H1 标题,以便元素本身的宽度由所用文本的数量定义?

在下面的示例中,我希望红色背景成为标题的宽度,但似乎无法发挥作用。

body {width; 100%; margin: 0;}

.holder {
  position: relative;
}

#events {
    margin: 1rem auto;
    background: red;
    text-align: center;
    width: auto;
}
<div class="holder">
    <h1 id="events">FUTURE THINGS</h1>
</div>  

display 类型更改为 inline-block

body {width; 100%; margin: 0;}

.holder {
  position: relative;
  /* To center the text */
  text-align:center;
}

#events {
    margin: 1rem auto;
    background: red;
    width: auto;
    display:inline-block;
}
<div class="holder">
    <h1 id="events">FUTURE THINGS</h1>
</div>

你可以使用display: inline-block来实现这个

#events {
    margin: 1rem auto;
    background: red;
    text-align: center;
    width: auto;
    display: inline-block; // Added
}

由于<h1>是块级元素,它将占据容器的整个宽度。如果您将 <h1> 设为 inline-blockinline 元素,它将满足您的要求。但我更喜欢在 <h1> 中添加 <span> 并为此应用背景颜色。所以 <h1> 仍然是块元素,这对布局很有帮助。由于 <span> 默认情况下在内联元素中,它将为您提供任何额外的样式。您再也不需要 <h1> 的包装器来维护布局。

h1{
  border-bottom: solid 1px black;
}
h1 span{
  background-color: red;
}
<h1 id="events">
  <span>FUTURE THINGS</span>
</h1>