Html 仅文本周围的背景颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13817506/
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
Background color only around text
提问by user1251698
I have an H1 in a div which is on more than 1 line because of fixed width of the div. I want to set the background color to H1 text only so that the background remains only behind the text (eg. if there is empty space in the end of the line, it should not use background color there).
由于 div 的固定宽度,我在 div 中有一个 H1,它位于 1 条以上的行上。我想将背景颜色设置为 H1 文本,以便背景仅保留在文本后面(例如,如果行尾有空格,则不应在那里使用背景颜色)。
Also, I need to set the left and right padding the text. I have tried to set the padding to the heading but it also does not work.
另外,我需要设置文本的左右填充。我试图将填充设置为标题,但它也不起作用。
Here's what I'm trying to get:
这是我想要得到的:
I am trying to achieve this by setting the inline
display for the H1, and setting background color, but it does not seem to work. Following is my HTML and CSS along with the demo.
我试图通过设置inline
H1的显示和设置背景颜色来实现这一点,但它似乎不起作用。以下是我的 HTML 和 CSS 以及演示。
HTML:
HTML:
<div class="box">
<h1>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin eget massa felis, at aliquam libero. </h1>
CSS:
CSS:
.box{
background: green;
overflow: hidden;
max-width: 100px;
margin: 50px auto;
padding: 20px;
}
h1{
background: yellow;
font-size: 30px;
float: left;
display: inline;
}
回答by Simone
The float: left
is not necessary. Remove it.
该float: left
是没有必要的。去掉它。
Also, you may want to decrease the line-height
so it looks like the demo (if you don't do this you will have blank lines under the text, which could be undesiderable).
此外,您可能希望减少line-height
它,使其看起来像演示(如果您不这样做,文本下方将有空行,这可能是不可取的)。