4

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/

1

2 Answers 2

8

Remove float:left in your h1

Demo

2
  • Thanks for the reply, but the problem is that i want to add the left and right padding to the heading, it does not seem to work. Dec 11, 2012 at 9:57
  • @user1251698, setting padding works normally, e.g. h1 { padding: 0 1em } adds 1em padding at the start and at the end. It seems that you want something else—probably something that you can achieve only by dividing the text in the heading into several elements, each to be displayed on a line of its own (with a fixed division into lines). Dec 11, 2012 at 10:51
1

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).

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.