[css] css h1 - only as wide as the text

I have an H1 style for my site:

.centercol h1 {
    color: #006bb6;
    font-weight: normal;
    font-size: 18px;
    padding:3px 3px 3px 6px;
    border-left:3px solid #c6c1b8;
    background:#f2efe9;
    display:block;
}

The background color spans the entire width of the centercol, 500px...

How do I make this H1 only span the width of the text of the H1?

This question is related to css

The answer is


An easy fix for this is to float your H1 element left:

.centercol h1{
    background: #F2EFE9;
    border-left: 3px solid #C6C1B8;
    color: #006BB6;
    display: block;
    float: left;
    font-weight: normal;
    font-size: 18px;
    padding: 3px 3px 3px 6px;
}

I have put together a simple jsfiddle example that shows the effect of the "float: left" style on the width of your H1 element for anyone looking for a more generic answer:

http://jsfiddle.net/zmEBt/1/


You can use display:inline-block to force this behavior


This is because your <h1> is the width of the centercol. Specify a width on the <h1> and use margin: 0 auto; if you want it centered.

Or, alternatively, you could float the <h1>, which would make it only exactly as wide as the text.


You could use a <span> instead of an <h1>.


.h1 {
  width: -moz-fit-content;
  width: fit-content;

  // workaround for IE11
  display: table;
}

All modern browsers support width: fit-content for that.

For IE11 we could emulate this behavior with display: table which doesn't break margin collapse like display: inline-block or float: left.


I recently solved this problem by using table-caption, though I cannot say if it is recommended. The other answers didn't seem to workout in my case.

h1 {
  display: table-caption;
}

Somewhat like the other suggestions you could use the following code. However, if you do go the margin: 0 auto; route I'd recommend having the margin for the top and bottom of an H1 be set to something other than 0. So, perhaps margin: 6px auto; or something.

.centercol h1{
    display: inline-block;
    color: #006bb6;
    font-weight: normal;
    font-size: 18px;
    padding:3px 3px 3px 6px;
    border-left:3px solid #c6c1b8;
    background:#f2efe9;
    display:block;
}

align-self-start, align-self-center... in flexbox

.centercol h1{
    background: #F2EFE9;
    border-left: 3px solid #C6C1B8;
    color: #006BB6;
    display: block;
    align-self: center;
    font-weight: normal;
    font-size: 18px;
    padding: 3px 3px 3px 6px;
}

You can use the inline-block value for display, however in this case you will loose the block feature of h1 i.e. the siblings will be displayed inline with h1 if they are inline elements(in which case you can use a line-break
).

display:inline-block;