开发者

Set background color through CSS for text only with line breaks

How would you go about applying a background color wit开发者_开发技巧h 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.


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}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜