Css – Width of Headers (H1, H2 etc)


I want my headers (h1 through h6) to have a background colour (different to that of the page background), I also want the width of this background to be the same as the width of the text in the header, plus padding (Not the width of the container that the header is in, which is what is happening now).

There isn't much point in me showing you any code as this is fairly simple (or it should be anyway!). The container is a fixed width. Right now I have just some margins, padding, background colour and font styling set for the h1, h2, h3 etc tags.

EDIT: I guess code would help! https://web.archive.org/web/20090724165158/http://adriantrimble.com/headers (this has Gerald's solution applied, although obviously this would still not work in IE6/7 and still has problems in newer browsers). Using display:inline causes more problems than it solves, using float: left and clear: left as mentioned has problems because of the 2 column layout. Thanks for everyones help so far.

Best Solution

h1-h6 are block level elements and even if they are not in a container (or just body) they'll stretch over the width of the window. One solution is to change their display to be inline-block instead:

<h1 style="background-color:pink; display:inline-block; padding:1em;">Testheader</h1>

Note that you'd have to make a manual break after the header if the next element isn't a block-level element like p.