Html 如何使用 CSS 设置文本宽度的背景颜色,而不是整个元素的宽度?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14310154/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 04:56:31  来源:igfitidea点击:

How do I set a background-color for the width of text, not the width of the entire element, using CSS?

htmlcss

提问by Hithere Paperbag

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:

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

h1 { 
    text-align: center; 
    background-color: green; 
}
<h1>The Last Will and Testament of Eric Jones</h1> 

回答by BalusC

Put the text in an inline element, such as a <span>.

将文本放在内联元素中,例如<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.

内联元素与其内容一样大,所以应该为你做。

回答by Hastig Zusammenstellen

Option 1

选项1

display: table;

display: table;

  • no parent required
  • 不需要父母

h1 {
    display: table; /* keep the background color wrapped tight */
    margin: 0px auto 0px auto; /* keep the table centered */
    padding:5px;font-size:20px;background-color:green;color:#ffffff;
}
<h1>The Last Will and Testament of Eric Jones</h1>

fiddle

小提琴

http://jsfiddle.net/J7VBV/293/

http://jsfiddle.net/J7VBV/293/

more

更多的

display: tabletells the element to behave as a normal HTML table would.

display: table告诉元素像普通的 HTML 表格一样表现。

More about it at w3schools, CSS Tricksand here

w3schoolsCSS Tricks这里有更多关于它的信息



Option 2

选项 2

display: inline-flex;

display: inline-flex;

  • requires text-align: center;on parent
  • 需要text-align: center;父母

.container {
    text-align: center; /* center the child */
}
h1 {
    display: inline-flex; /* keep the background color wrapped tight */
    padding:5px;font-size:20px;background-color:green;color:#ffffff;
}
<div class="container">
  <h1>The Last Will and Testament of Eric Jones</h1>
</div>



Option 3

选项 3

display: flex;

display: flex;

  • requires a flex parent container
  • 需要一个 flex 父容器

.container {
  display: flex;
  justify-content: center; /* center the child */
}
h1 {
    display: flex;
    /* margin: 0 auto; or use auto left/right margin instead of justify-content center */
    padding:5px;font-size:20px;background-color:green;color:#ffffff;
}
    <div class="container">
      <h1>The Last Will and Testament of Eric Jones</h1>
    </div>

about

关于

Probably the most popular guide to Flexbox and one I reference constantly is at CSS Tricks

可能最流行的 Flexbox 指南和我经常参考的指南是CSS Tricks



Option 4

选项 4

display: block;

display: block;

  • requires a flex parent container
  • 需要一个 flex 父容器

.container {
  display: flex;
  justify-content: center; /* centers child */
}
h1 {
    display: block;
    padding:5px;font-size:20px;background-color:green;color:#ffffff;
}
<div class="container">
  <h1>The Last Will and Testament of Eric Jones</h1>
</div>



Option 5

选项 5

::before

::before

  • requires entering words in css file (not very practical)
  • 需要在 css 文件中输入单词(不太实用)

h1 {
    display: flex; /* set a flex box */
    justify-content: center; /* so you can center the content like this */
}

h1::before {
    content:'The Last Will and Testament of Eric Jones'; /* the content */
    padding: 5px;font-size: 20px;background-color: green;color: #ffffff;
}
<h1></h1>

fiddle

小提琴

http://jsfiddle.net/J7VBV/457/

http://jsfiddle.net/J7VBV/457/

about

关于

More about css pseudo elements ::before and ::after at CSS Tricksand pseudo elements in general at w3schools

更多关于 CSS 伪元素 ::before 和 ::after 在CSS Tricks和伪元素一般在w3schools



Option 6

选项 6

display: inline-block;

display: inline-block;

  • centering with position: absoluteand translateX

  • requires a position: relativeparent

  • position: absolute和为中心translateX

  • 需要position: relative父母

.container {
  position: relative; /* required for absolute positioned child */
}
h1 {
  display: inline-block; /* keeps container wrapped tight to content */
  position: absolute; /* to absolutely position element */
  top: 0;
  left: 50%; /* part1 of centering with translateX/Y */
  transform: translateX(-50%); /* part2 of centering with translateX/Y */
  white-space: nowrap; /* text lines will collapse without this */
  padding:5px;font-size:20px;background-color:green;color:#ffffff;
}
  <h1>The Last Will and Testament of Eric Jones</h1>

about

关于

More on centering with transform: translate();(and centering in general) in this CSS tricks article

transform: translate();这篇 CSS 技巧文章中更多地了解居中(和一般居中)



Option 7

选项 7

text-shadow:and box-shadow:

text-shadow:box-shadow:

  • not what the OP was looking for but maybe helpful to others finding their way here.
  • 不是 OP 正在寻找的东西,但可能有助于其他人在这里找到自己的方式。

h1, h2, h3, h4, h5 {display: table;margin: 10px auto;padding: 5px;font-size: 20px;color: #ffffff;overflow:hidden;}
h1 {
    text-shadow: 0 0 5px green,0 0 5px green,
                 0 0 5px green,0 0 5px green,
                 0 0 5px green,0 0 5px green,
                 0 0 5px green,0 0 5px green;
}
h2 {
    text-shadow: -5px -5px 5px green,-5px 5px 5px green,
                  5px -5px 5px green,5px 5px 5px green;
}
h3 {
    color: hsla(0, 0%, 100%, 0.8);
    text-shadow: 0 0 10px hsla(120, 100%, 25%, 0.5),
                 0 0 10px hsla(120, 100%, 25%, 0.5),
                 0 0 10px hsla(120, 100%, 25%, 0.5),
                 0 0 5px hsla(120, 100%, 25%, 1),
                 0 0 5px hsla(120, 100%, 25%, 1),
                 0 0 5px hsla(120, 100%, 25%, 1);
}
h4 { /* overflow:hidden is the key to this one */
    text-shadow: 0px 0px 35px green,0px 0px 35px green,
                 0px 0px 35px green,0px 0px 35px green;
}
h5 { /* set the spread value to something larger than you'll need to use as I don't believe percentage values are accepted */
  box-shadow: inset 0px 0px 0px 1000px green;
}
<h1>The First Will and Testament of Eric Jones</h1>
<h2>The 2nd Will and Testament of Eric Jones</h2>
<h3>The 3rd Will and Testament of Eric Jones</h3>
<h4>The Last Will and Testament of Eric Jones</h4>
<h5>The Last Box and Shadow of Eric Jones</h5>

fiddle

小提琴

https://jsfiddle.net/Hastig/t8L9Ly8o/

https://jsfiddle.net/Hastig/t8L9Ly8o/

More Options

更多选择

There are a few other ways to go about this by combining the different display options and centering methods above.

通过结合上面的不同显示选项和居中方法,还有其他一些方法可以解决这个问题。

回答by Dan

A little late to game but thought I would add my 2 cents...

游戏有点晚了,但我想我会加我的 2 美分...

To avoid adding the extra mark-up of an inner span you could change the <h1>display property from blockto inline(catch is you would have ensure the elements after the <h1>are block elements.

为避免添加内部跨度的额外标记,您可以将<h1>显示属性从blockto更改为inline(注意,您必须确保<h1>块元素之后的元素。

HTML

HTML

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

CSS

CSS

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

Result
enter image description here
JSFIDDLE http://jsfiddle.net/J7VBV/

结果
在此处输入图片说明
JSFIDDLE http://jsfiddle.net/J7VBV/

回答by Starx

A very simple trick to do so, is to add a <span>tag and add background color to that. It will look just the way you want it.

这样做的一个非常简单的技巧是添加一个<span>标签并为其添加背景颜色。它看起来就像你想要的那样。

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

And CSS

和 CSS

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

WHY?

为什么?

<span>tag in an inline element tag, so it will only span over the content faking the effect.

<span>内联元素标签中的标签,因此它只会跨越伪造效果的内容。

回答by JGallardo

EDIT: the answer below would apply in most cases. OP however later mentioned that they could not edit anything other than the CSS file. But will leave this here so it may be of use to others.

编辑:下面的答案适用于大多数情况。OP 但是后来提到他们不能编辑除 CSS 文件以外的任何内容。但是将其留在这里,以便对其他人有用。

enter image description here

在此处输入图片说明

The main consideration that others are neglecting is that OP has stated that they cannot modify the HTML.

其他人忽略的主要考虑因素是 OP 已声明他们不能修改 HTML。

You can target what you need in the DOM then add classes dynamically with javascript. Then style as you need.

您可以在 DOM 中定位您需要的内容,然后使用 javascript 动态添加类。然后根据需要设计样式。

In an example that I made, I targeted all <p>elements with jQuery and wrapped it with a div with a class of "colored"

在我制作的一个例子中,我<p>用 jQuery定位所有元素,并用一个“colored”类的 div 包裹它

$( "p" ).wrap( "<div class='colored'></div>" );

Then in my CSS i targeted the <p>and gave it the background color and changed to display: inline

然后在我的 CSS 中,我定位<p>并给了它背景颜色并更改为display: inline

.colored p {
    display: inline;
    background: green;
}

By setting the display to inline you lose some of the styling that it would normally inherit. So make sure that you target the most specific element and style the container to fit the rest of your design. This is just meant as a working starting point. Use carefully. Working demo on CodePen

通过将显示设置为内联,您会丢失一些它通常会继承的样式。因此,请确保针对最具体的元素并设置容器样式以适合您设计的其余部分。这只是一个工作起点。小心使用。CodePen 上的工作演示

回答by Coburn

As the other answers note, you can add a background-colorto a <span>around your text to get this to work.

正如其他答案所指出的,您可以在文本周围添加 abackground-color<span>使其工作。

In the case where you have line-heightthough, you will see gaps. To fix this you can add a box-shadowwith a little bit of grow to your span. You will also want box-decoration-break: clone;for FireFox to render it properly.

如果你有line-height,你会看到差距。要解决此问题,您可以box-shadow在跨度上添加一点点增长。您还需要box-decoration-break: clone;FireFox 正确渲染它。

EDIT: If you're getting issues in IE11 with the box-shadow, try adding an outline: 1px solid [color];as well for IE only.

编辑:如果您在 IE11 中遇到带有 box-shadow 的问题,请尝试outline: 1px solid [color];仅为 IE添加一个。

Here's what it looks like in action:

这是它的实际运行情况:

example of the css technique

css技术的例子

.container {
  margin: 0 auto;
  width: 400px;
  padding: 10px;
  border: 1px solid black;
}

h2 {
  margin: 0;
  padding: 0;
  font-family: Verdana, sans-serif;
  text-transform: uppercase;
  line-height: 1.5;
  text-align: center;
  font-size: 40px;
}

h2 > span {
  background-color: #D32;
  color: #FFF;
  box-shadow: -10px 0px 0 7px #D32,
    10px 0px 0 7px #D32,
    0 0 0 7px #D32;
  box-decoration-break: clone;
}
<div class="container">
    <h2><span>A HEADLINE WITH BACKGROUND-COLOR PLUS BOX-SHADOW :3</span></h2>
</div>

回答by Andy

h1 is a block level element. You will need to use something like span instead as it is an inline level element (ie: it does not span the whole row).

h1 是块级元素。您将需要使用类似 span 的东西,因为它是一个内联级别元素(即:它不会跨越整行)。

In your case, I would suggest the following:

在你的情况下,我建议如下:

style.css

样式文件

.highlight 
{
   background-color: green;
}

html

html

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

回答by AgnosticDev

Try removing the text-alignment center and center the <h1>or <div>the text resides in.

尝试移除文本对齐中心并将文本所在的<h1><div>文本居中。

h1 {
    background-color:green;
    margin: 0 auto;
    width: 200px;
}

回答by Ravi Panchal Vishwakarma

can use html5 marktag within paragraph and heading tag.

可以在段落和标题标签中使用 html5标记标签。

<p>lorem ipsum <mark>Highlighted Text</mark> dolor sit.</p>

回答by Dan Bray

You can use the HTML5 <mark>tag.

您可以使用 HTML5<mark>标记。

HTML:

HTML:

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

CSS:

CSS:

mark
{
    background-color: green;
}