I want to style an H3 header with a background colour. If I do this:

h3 {
 background-color: #000;
 color: #fff;


<h3>header tag</h3>

for example, the output in the browser will be displayed across the entire width of it's parent container. If I wrap "header tag" in a <span> tag instead of a div, that the background colour would 'span' the text only.

Is there a way to style an H3 tag so the background colour will 'span' the text of H3 only?

I want to know if this is possible so I can continue to write H3 tags instead of say <span class=h3></span>

Recommended Answers

All 5 Replies

<h3><span>content in here</span></h3>

h3 span{css in here}

You do know you can give the h3 tag a width...

Also <span class="h3"> </span> is probably invalid, as h3 is reserved as a tag name.


I was trying to get away without using the SPAN stags and just using the header tags.

With regards adding width to header tags, yes I did know that, and tried it. The problem
I found was that the width is only to the with of the parent container, not the text length and/or size of the text, which means you would have to adjust the width each time, depending on the length of the text between the tags.

Using your example:

h3 {
 background-color: #000;
 color: #fff;
 display: inline;

display:inline-block; is not supported in ie, but display:inline; seems to work in all I've tried.

Member Avatar for diafol

How about setting the span display to inline-block? Will this give it an automatic content width? Think IE6/7 may have an issue with certain elements set to this - read somewhere that only naturally inline elements (like span) will work with inline-block. Haven't tried it though.


Sorry, didn't read previous posts. Disregard if you don't want spans. Doh!

inline-block with just h3 - worked for me in Chrome, but failed in IE.

adding the 'display:inline' worked in my dev environment (firefox/chrome/opera in Linux). Although I haven't tested yet under any IE ver browsers, according to w3school, it will be OK but 'inline-block' wont.

Thanks for the help chaps.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.