The reason behind the background color
stretching to full width is due to the nature of <h1>
elements being block elements. Block elements automatically try to occupy the entire available width within their parent element. Therefore, when the parent element already spans the full width of the page, the <h1>
element will also extend to that width. For example, in the third case where the <h1>
container has a max-width: 50%
, the <h1>
element will utilize all the remaining width.
There are multiple ways to address this issue. Personally, I find that using width: fit-content
is most effective as it sets the width of the <h1>
element equal to its content. However, it's worth noting that not all browsers fully support this property. It is recommended to use the Firefox prefix for broader compatibility.
h1 {
background-color: limegreen;
}
.fit-content {
width: fit-content;
width: -moz-fit-content;
}
.inline-block {
display: inline-block;
}
div {
max-width: 50%;
}
<h1>standard h1</h1>
<h1 class="fit-content">fit-content</h1>
<h1 class="inline-block">inline-block</h1>
<div>
<h1 class="with-parent">with parent</h1>
</div>