Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

css background color extend as far as text?

Tags:

css

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.

like image 483
Matt Avatar asked Dec 19 '11 22:12

Matt


2 Answers

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/

like image 182
eveevans Avatar answered Oct 19 '22 19:10

eveevans


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;
}
like image 31
lonesomeday Avatar answered Oct 19 '22 18:10

lonesomeday