如何使用CSS为文本的宽度而不是整个元素的宽度设置背景色? [英] How do I set a background-color for the width of text, not the width of the entire element, using CSS?

查看:73
本文介绍了如何使用CSS为文本的宽度而不是整个元素的宽度设置背景色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要的是绿色背景位于文本的后面,而不是页面宽度的100%.这是我当前的代码:

What I want is for the green background to be just behind the text, not to be 100% of the page width. Here is my current code:

h1 { 
    text-align: center; 
    background-color: green; 
}

<h1>The Last Will and Testament of Eric Jones</h1> 

推荐答案

将文本放在内联元素,例如<span>.

<h1><span>The Last Will and Testament of Eric Jones</span></h1>

然后将背景色应用于内联元素.

And then apply the background color on the inline element.

h1 {
    text-align: center; 
}
h1 span { 
    background-color: green; 
}

内联元素的大小与其内容一样大,因此应该为您做到这一点.

An inline element is as big as its contents is, so that should do it for you.

这篇关于如何使用CSS为文本的宽度而不是整个元素的宽度设置背景色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆