我想要的是绿色背景刚好在文本的后面,而不是100%的页面宽度。这是我当前的代码:

h1 { text-align:中心; 背景颜色:绿色; } <h1>埃里克·琼斯最后的遗嘱和遗嘱<h1>


当前回答

<mark>标签与背景颜色帮助我。

输入:

<p>
    Effective <mark style="background-color: light-gray">Nov 1, 2022</mark> We will be lowering our price.
</p>

输出: 自2022年11月1日起,我们将降低价格。

Ref

其他回答

有点晚了,但我想补充一下我的意见……

为了避免添加额外的内span标记,您可以将<h1>显示属性从块更改为内联(catch是您必须确保<h1>之后的元素是块元素。

HTML

<h1>  
The Last Will and Testament of
Eric Jones</h1> 
<p>Some other text</p>

CSS

h1{
    display:inline;
    background-color:green;
    color:#fff;
}

结果 JSFIDDLE http://jsfiddle.net/J7VBV/

一个非常简单的技巧是添加一个<span>标记,并为其添加背景色。它会变成你想要的样子。

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

和CSS

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

WHY?

<span>标记在一个内联元素标记中,因此它将只跨越伪造效果的内容。

很容易:

<p>lorem ibsum....</p>

样式:

p{
    background-color: #eee;
    display: inline;
}


背景设置为元素的整体大小; 从这里修改内联元素和块元素之间的区别

H1是块级元素。你需要使用像span这样的东西,因为它是一个内联级元素(即:它不跨越整行)。

针对你的情况,我建议如下:

style.css

.highlight 
{
   background-color: green;
}

html

<span class="highlight">only the text will be highlighted</span>

你必须提到h1标签的宽度..

你的CSS是这样的

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