WhoDidYouSay
WhoDidYouSay

Reputation: 23

How to limit the background colour I put on text

How can I limit the length of the background colour I place on text?

I'm messing around with a pretty basic site just to re-jog my memory of HTML and all the different elements, I'm using an external stylesheet and I have used this code:

li:nth-child(4) {
    background: yellow;
}

and the line that this is affecting is:

<li>And this will have a yellow background!</li>

Now, the colour does show up only it highlights the text and the rest of the webpage line that the text is sat on, how do I set it so that the text and nothing else has a background? Is there a simple css solution or will I have to resort to placing it within a div tag?

Upvotes: 2

Views: 1739

Answers (1)

wickywills
wickywills

Reputation: 4214

Because the LI will automatically stretch to the rest of the page. Just add the following to your LI style:

display:inline-block;

And that should hopefully solve the problem.

That will display the LI's in a horizontal line however. An alternative would be to add another element within the LI e.g. a <span>

So:

<li>And this will have a yellow background!</li>

Becomes:

<li><span>And this will have a yellow background!</span></li>

And then just do something like this in your CSS:

li:nth-child(4)>span { background:yellow; }

See Fiddle here

Upvotes: 4

Related Questions