CSS:文本大小的背景颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9128902/
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
CSS: Background color to text size
提问by Mc-
I'm would like to color the background of a text but only to it's size.
我想为文本的背景着色,但仅限于它的大小。
Images are better than a thousand words, here is what I'm trying to achieve:
图片胜过千言万语,这就是我想要实现的目标:
And this is what I am achieving
这就是我正在实现的目标
I don't want to do this programmatically, I would like the background to adapt to the text ( because it may be dynamic )
我不想以编程方式执行此操作,我希望背景适应文本(因为它可能是动态的)
Is there anyway to do this without using javascript?
有没有办法在不使用javascript的情况下做到这一点?
Update (HTML):
更新(HTML):
<div class="team-member-teaser-name">OSCAR</div>
CSS
CSS
.team-member-teaser-name
{
color: #4fb4d0;
background: #135364;
margin-top: 5px;
margin-bottom: 5px;
padding-left: 5px;
font-size: 10px;
}
Update(Solved, based on @BoldClock answer):
更新(已解决,基于@BoldClock 答案):
.team-member-teaser-name
{
color: #4FB4D0;
background: #135364;
margin-top: 5px;
padding-left: 5px;
font-size: 10px;
display: inline;
float: left;
padding-right: 9px;
clear: both;
}
I don't really understand how clear works, but is required to achieve the results on the image.
我真的不明白 clear 是如何工作的,但需要在图像上实现结果。
回答by BoltClock
You need to apply the background color to an inline element. If the text is in a block element, you need to wrap the text in an inline child of the block element (assuming it's not feasible to put display: inline
on the block element). And if you can't edit the HTML, you will have to do it within a script.
您需要将背景颜色应用于内联元素。如果文本在块元素中,则需要将文本包裹在块元素的内联子元素中(假设放在display: inline
块元素上是不可行的)。如果您无法编辑 HTML,则必须在脚本中进行。
回答by Wertisdk
You could wrap your text in a span like this:
您可以像这样将文本包裹在一个跨度中:
<p><span class="highlight">OSCAR</span></p>
and then, depending on you current css you could style it like this:
然后,根据您当前的 css,您可以像这样设置样式:
.highlight{
background-color: blue;
}
回答by Sagar Patil
Use the background
property to define a background color. For eg,
使用该background
属性定义背景颜色。例如,
<a href="#">oscar</a>
a{ background:#ff0000; }
If you have inline elements such as a <span />
or <a />
you can add display:block
to the styles if you want to define a height and width on the element. Additionally, you can also define a padding on the element if you want to control the spacing area around the text to give your text some breathing room.
如果你有行内元素,如<span />
或<a />
您可以添加display:block
,如果你要定义一个高度和宽度的元素的样式。此外,如果您想控制文本周围的间距区域以给文本一些喘息空间,您还可以在元素上定义内边距。