Ashish
Ashish

Reputation: 61

Limiting background-color to width of heading

I am trying to get a background color to stick strictly to the text of the heading and not span the entire width of the page. I understand that block level elements take up the entire width of the page, so I was wondering if there was a way around this besides forcing inline styles.

EDIT: If I were to use display: inline-block; why is it that even though I specify text-align: center; my headers are still left aligned? Should I use a float instead?

Upvotes: 6

Views: 16131

Answers (4)

manojadams
manojadams

Reputation: 2429

You must specify the text-align:center; attribute to the parent element containing your div block to center your header and its background with display:inline-block;

Upvotes: 0

Selçuk
Selçuk

Reputation: 176

This would solve this problem I think:

<div id="Heading">
   <div id="HeadingText">HEADING TEXT</div>
</div>

And your css would be:

#Heading{
    background-color:#CCC;
}
#HeadingText{
    display:inline-block;
    background-color:#FF0000;
}

Upvotes: 0

Jameson
Jameson

Reputation: 6669

Or displaying as an inline-block could meet most use cases:

h1 { background-color: red; display: inline-block; }

Upvotes: 5

CatShoes
CatShoes

Reputation: 3733

Perhaps something like this:

In HTML:

<div id="Heading">
   <span id="HeadingText">HEADING TEXT</span>
</div>

In CSS:

#Heading
{
   /* Formatting of full heading */
}

#HeadingText
{
   /* Formatting for just heading text */
   background-color: #00ff00;
}

Guessing from your question, this isn't the answer you are looking for, but it may be useful.

EDIT:

Alternatively, this should work as well. But I'm pretty sure this is what you want to avoid (inline, right?)...

<h1 style="background-color:#660000; display:inline;">Heading<h1>

Upvotes: 1

Related Questions