Matt
Matt

Reputation: 2509

css background color extend as far as text?

How would I set the background color of a text that doesn't expand to width of its parent div? I used h1 {background color:white;} and wrapped h1 around the text I want, but the white background just extends beyond text. It's almost like you're just highlighting the words.

Upvotes: 9

Views: 34816

Answers (2)

eveevans
eveevans

Reputation: 4460

h1 is a block element, so , it will use all the available area. so change this element to inline, for only use its width

h1 {
  display: inline;
  background-color: white;
}

http://jsfiddle.net/wxNQR/

Upvotes: 19

lonesomeday
lonesomeday

Reputation: 237865

The trouble is that h1 is a block-level element, and by default block level elements will expand to fill all the available width of the parent element.

The easiest way to solve this is to float the element:

h1 {
    background-color: white;
    float: left;
}

You will then need to style the following paragraph, so that it doesn't flow round the heading element:

p {
    clear: left;
}

If you are comfortable not supporting IE7 and below, you can use the adjacent sibling selector to make this selection neater, so that only p elements directly after h1 elements will be so styled:

h1 + p {
    clear: left;
}

Upvotes: 3

Related Questions