Reputation: 947
How do i get an H1 heading so the element itself has its width defined by the amount of text used?
In the example below I want the red background to be the width of the title but can't seem to get this to play ball.
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>
Upvotes: 1
Views: 2233
Reputation: 2261
Since <h1>
is a block level element, it will occupy the full width of the container. If you make <h1>
an inline-block
or inline
element, it will satisfy your requirement. But I prefer to add <span>
inside <h1>
and apply background color for that. So the <h1>
remains as block element and which can be helpful in the layout. Since <span>
in inline element by default, it will serve you with out any additional styles. You never need anymore wrapper for the <h1>
to maintain the layout.
h1{
border-bottom: solid 1px black;
}
h1 span{
background-color: red;
}
<h1 id="events">
<span>FUTURE THINGS</span>
</h1>
Upvotes: 1
Reputation: 3473
you can use display: inline-block
to achieve this
#events {
margin: 1rem auto;
background: red;
text-align: center;
width: auto;
display: inline-block; // Added
}
Upvotes: 1
Reputation: 14348
Change display
type to 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>
Upvotes: 4