I am trying to wrap a background colour around an h1 and h2 hag with CSS. However, as these are block elements the background is full width and what I require is just to make the background 5px around the text in the heading tag.

If you look at the example I have the text "About", I just want the background to be black 5px around this text ?

How do I do this, I tried to make them display:inline but that messed up my layout.

Cheers

  • I don't know of any way to make the width of an h1 only as large as its content without setting the display to inline (or floating it, but that would probably cause even more problems in this case). I'm curious to see if anyone comes up with a good answer for you. Michael Martin-Smucker about 6 years ago

3 answers

Tony B 86
0
points

You could try making an image of the text with its background and replacing the h1 sort of like a sprite with text-indent -9999px. The other way I can think of is to float the element, assign the appropriate values for width and height that you want and plan accordingly with other content that will be around it.

Answered about 6 years ago by Tony B
0
points

You can make the elements display:inline, but you'll lose the default (or custom) margins on the elements. Or you could float:left those elements, and use clearfix to make sure everything below them clears, so there are no problems.

Answered about 6 years ago by webcodeslinger
0
points

Apologies for firing up an old post. Had a similar problem. I used display: inline-block; to fix a problem I had with bottom border on a h2 using 100% width of parent element, works in Safari, FF, Chrome, IE8, Opera on XP.

Answered over 5 years ago by Kenneth Purtell