8

我在使用 css 的 line-height + text 背景样式方面遇到问题。

<style>
.wrap  {
    width: 70%; 
    line-height:0.9;
}
.hl {

        background-color: orange;
}
</style>
<div class="wrap">
       <span class="hl">
          Some content will go here which will be split into several lines depending of resolution (depending on width of wraper)
       </span>
</div>

我有根据浏览器宽度换行为多行的动态文本此文本的行高小于“正常”。当我将背景颜色应用于文本时,此背景与下行字母的底部重叠:g、p、y、q、j

在此处输入图像描述 似乎文本在浏览器中呈现,使得第二行/下一行文本(及其背景颜色)位于第一行/上一行文本的前面,因此第二行的背景位于下行字母的前面到行高。

每一行都有一个新的背景,因为我们正在谈论一个内联元素。我当然需要使用内联元素来获取文本背景。我需要用css或JS来解决这个问题,而不改变文本的文本行高。

附加信息:我在这里找到了一个很好的答案: 在每行文本的开头和结尾添加填充

由三十多点回答(在问题下方接受答案),但如果你检查他的现场演示解决方案,并将那里的 line-height 更改为更小的值,你会遇到和我一样的问题。 演示

4

5 回答 5

3

因为你line-height的更少,我可以看到你正在为你的文本应用背景颜色,所以line-height在没有指定单位的情况下增加你的和更多,比如empx你的line-height属性,顺便说一句,不需要添加填充

尝试这个 :

line-height:25px;

更多信息:您需要提供,inline-block;因为您使用的是跨度,您可以简单地使用 adiv代替

于 2012-10-29T08:20:06.593 回答
1

一种解决方案:如果你想保持你的行高小于“正常”,而不是使用彩色背景,使用重复的 png 图像。在此 png 的顶部添加一个透明区域,该区域等于重叠的高度。:)

于 2012-10-29T17:39:57.000 回答
1

将文本包裹在跨度内并将跨度位置设置为相对。这会做!

CSS:

.your-backgrounded-h1-class span { position: relative; }

HTML:

<h1 class="your-backgrounded-h1-class"><span>Your Text!</span></h1>
于 2015-04-27T21:28:21.053 回答
1

<span> display: inline-block;

.wrap {
  width: 70%;
  line-height: 0.9;
}

.hl {
  font-size: 3em;
  background-color: orange;
  display: inline-block;
}
<div class="wrap">
  <span class="hl">
          Some content will go here which will be split into several lines depending of resolution (depending on width of wraper)
       </span>
</div>

于 2020-01-24T07:06:53.603 回答
1

对于任何对当前答案不满意的人,我找到了一个解决方案,它允许任何line-height并且适用于跨行的文本。使用渐变background-image。您可能需要根据需要调整百分比。

background-image: linear-gradient(to bottom, transparent, transparent 17%, orange 17%, orange);
于 2020-10-07T02:14:20.900 回答