简体   繁体   中英

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?

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 eg 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM