user1251698
user1251698

Reputation: 2143

Background color only around text

I have an H1 in a div which is on more than 1 line because of fixed width of the div. I want to set the background color to H1 text only so that the background remains only behind the text (eg. if there is empty space in the end of the line, it should not use background color there).

Also, I need to set the left and right padding the text. I have tried to set the padding to the heading but it also does not work.

Here's what I'm trying to get:

enter image description here

I am trying to achieve this by setting the inline display for the H1, and setting background color, but it does not seem to work. Following is my HTML and CSS along with the demo.

HTML:

<div class="box">
    <h1>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin eget massa felis, at aliquam libero. </h1>

CSS:

.box{
    background: green;
    overflow: hidden;
    max-width: 100px;
    margin: 50px auto;
    padding: 20px;
}

h1{   
    background: yellow;
    font-size: 30px;   
    float: left;
    display: inline;   
}

Demo: http://jsfiddle.net/BQMXa/

Upvotes: 4

Views: 36152

Answers (2)

Simone
Simone

Reputation: 21262

The float: left is not necessary. Remove it.

Also, you may want to decrease the line-height so it looks like the demo (if you don't do this you will have blank lines under the text, which could be undesiderable).

Upvotes: 1

Rohit Azad Malik
Rohit Azad Malik

Reputation: 32152

Remove float:left in your h1

Demo

Upvotes: 8

Related Questions