CSS:背景颜色到文本大小
我想为文本的背景着色,但仅限于它的大小。
图像胜过一千个单词,这就是我想要实现的目标:
这就是我正在实现
我不想以编程方式执行此操作,我希望背景能够适应文本(因为它可能是动态的)
有没有办法在不使用javascript的情况下做到这一点?
更新(HTML):
<div class="team-member-teaser-name">OSCAR</div>
CSS
.team-member-teaser-name
{
color: #4fb4d0;
background: #135364;
margin-top: 5px;
margin-bottom: 5px;
padding-left: 5px;
font-size: 10px;
}
更新(已解决,基于@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;
}
我不太明白clear是如何工作的,但需要在图像上实现结果。
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?
Update (HTML):
<div class="team-member-teaser-name">OSCAR</div>
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):
.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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要将背景颜色应用于内联元素。如果文本位于块元素中,则需要将文本包装在块元素的内联子元素中(假设将
display: inline
放在块元素上不可行)。如果您无法编辑 HTML,则必须在脚本中进行编辑。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.你可以将你的文本包装在一个像这样的跨度中:
然后,根据你当前的CSS,你可以像这样设置它的样式:
You could wrap your text in a span like this:
and then, depending on you current css you could style it like this:
使用
background
属性定义背景颜色。例如,如果您有内联元素,例如
或
您可以添加
display:block
如果要定义元素的高度和宽度,请添加到样式。此外,如果您想控制文本周围的间距区域以便为文本提供一些喘息空间,您还可以在元素上定义填充。Use the
background
property to define a background color. For eg,If you have inline elements such as a
<span />
or<a />
you can adddisplay: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.