Search code examples
htmlcsswidth

Apply Auto Width to an H1 Heading


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>  


Solution

  • 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>