Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Background color only around text

Tags:

html

css

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/

like image 725
user1251698 Avatar asked Feb 18 '23 05:02

user1251698


2 Answers

Remove float:left in your h1

Demo

like image 161
Rohit Azad Malik Avatar answered Mar 04 '23 02:03

Rohit Azad Malik


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

like image 42
Simone Avatar answered Mar 04 '23 01:03

Simone