David K.
David K.

Reputation: 324

Set background color through CSS for text only with line breaks

How would you go about applying a background color with CSS only, while only applying the color to visible text.

I am trying to achieve the following:

<div style="width:200px;background-color:white;">
<p style="background-color:red;color:black;">This text is longer than 200 pixel and therefore a line break will occur</p>
</div>

Unfortunately the background is applied to the full with of the <p>-tag and not ending with the last character before the line break occurs. On the side note, I am NOT able to line break the displayed text manually.

So if the output the above would look like this:

----------this line is exactly 200px----------
This text is longer than 200 pixel and
therefore a line break will occur
----------------------------------------------

So the background-color should end with the word "and" on the first line and end with the word "occur" on the second line, leaving the background of the <div> white.

I am really pulling my hair out and would love to get input if this is even possible without manually setting line breaks? I'd go with a javascript solution too, but prefer a css only one.

Upvotes: 2

Views: 14993

Answers (1)

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114367

Paragraphs are block elements - they take up the width of their containers, not their content.

You need to use <span> instead of <p> to get the desired effect.

Alternately you and make <p> an inline element, but this may break other aspects of your page.

p {display:inline}

Upvotes: 8

Related Questions