CSS 为文本添加背景颜色,但在段落行之间留有空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2527765/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 21:49:36  来源:igfitidea点击:

Add a background color to text, but with space blank space between lines of paragraph

css

提问by Chris

I was wondering if something was possible to do in CSS. Basically i want to recreate the text on the RHS of the image using html/css, but currently I'm getting the LHS of the image.

我想知道是否可以在 CSS 中做一些事情。基本上我想使用 html/css 在图像的 RHS 上重新创建文本,但目前我正在获取图像的 LHS。

The HTML:

HTML:

<div id="banner">
    <div id="text">
        <p>This is an example of what I have</p>
    </div>
</div>

The CSS:

CSS:

div#banner { background: green; width:300px; height:300px;}
div#text {  margin: 20px auto; }
div#text p {  background:#fff; padding: 5px; margin: 5px; font-size: 2em; }

Now I realise that this can be done already either by:

现在我意识到这可以通过以下方式完成:

  1. Using an image
  2. Using separate p tags
  1. 使用图像
  2. 使用单独的 p 标签

(By Point 2 I mean:

(第 2 点我的意思是:

<div id="banner">
    <div id="text">
        <p>This is an</p>
        <p>example of</p>
        <p>what I have</p>
    </div>
</div>

)

)

But what I would really like to know is if it's actually possible to do what is on the RHS of the image, using only css and a single p tag?

但我真正想知道的是,是否真的可以仅使用 css 和单个 p 标签来执行图像 RHS 上的操作?

alt text http://chris.carrotmedialtd.com/example.jpg

替代文字 http://chris.carrotmedialtd.com/example.jpg

回答by Dexter

You can achieve your desired effect by using:

您可以使用以下方法达到您想要的效果:

  • display: inline;to force the background styling on the p to apply to the text, rather than the block on the p, and
  • line-height: 2.2em(slightly more than your font size) to force lines between your text
  • display: inline;强制 p 上的背景样式应用于文本,而不是 p 上的块,以及
  • line-height: 2.2em(略大于您的字体大小)强制您的文本之间的线条

like such:

像这样:

div#text p {
    display: inline;
    background: #fff;
    padding: 5px;
    margin: 5px;
    font-size: 2em;
    line-height: 2.2em;
}

回答by Todd Yandell

Because a paragraph tag is a block element, the background will be painted between lines. If you change it to an inline element, or wrap the text in an inline element, you should be able to get the effect you want.

因为段落标签是块元素,所以背景会在行之间绘制。如果你把它改成内联元素,或者将文本包裹在一个内联元素中,你应该能够得到你想要的效果。

<p><span>This is an example of what I have</span></p>

span {
   background: #fff;
}