简体   繁体   English

CSS:多行文本上的透明背景色,没有难看的重叠或行间距

[英]CSS: Transparent background-color on multi-line text, without ugly overlap or space between lines

I am overlaying white text with a semi-transparent background over an image. 我在图像上覆盖了半透明背景的白色文本。 For single lines, this works great. 对于单线,这很好用。 However, when the text is multi-line, the transparent background overlaps the lines below and above and create an ugly box in between each line where the overlap occurs. 但是,当文本是多行时,透明背景与下方和上方的线重叠,并在发生重叠的每一行之间创建一个丑陋的框。 Nor do I want empty space in between lines either, say if the line height is large -- I'm looking for a uniform transparent background in the shape of the text. 我也不想在线之间留空空间,比如线高是否很大 - 我正在寻找文本形状的统一透明背景。

Here's an codepen example of the overlap in action: 这是动作中重叠的codepen示例:

https://codepen.io/haydentech/pen/oeQpXe https://codepen.io/haydentech/pen/oeQpXe

<h1 class="padded-multiline">
  <span>How can I have multiline text with a transparent background, without these ugly boxes between lines?</span>
</h1>

.

.padded-multiline { 
  line-height: 1.4; 
  padding: 2px 0; 
  width: 400px;
  margin: 20px auto;
}

.padded-multiline span { 
  background: rgba(0, 0, 0, 0.5);
  color: #fff; 
  display: inline;
  padding: 0.45rem;
  box-decoration-break: clone;
  -webkit-box-decoration-break: clone;
}

body {
  background: linear-gradient(to right, lightblue, yellow);
}

If the line-height were calculated perfectly (1.63 in the above example), then there would be no overlap or empty space between lines. 如果完美地计算了线高(在上面的例子中是1.63),那么线之间将没有重叠或空的空间。 However, getting that calculated perfectly down to the pixel on all browsers is a fool's errand, so I'm not really interested in going there, especially since my font size may vary between desktop and mobile. 然而,将计算结果完美地计算在所有浏览器上的像素是一个愚蠢的差事,所以我真的不想去那里,特别是因为我的字体大小可能因桌面和移动设备而异。

If using inline-block doesn't cut the deal for your, a good hack would be to use box-shadow to complete the "unfilled" holes between lines: 如果使用内联块不能减少您的交易,那么一个好的黑客就是使用box-shadow来完成线之间的“未填充”漏洞:

.padded-multiline span { 
  box-shadow: 0 -5px 0 rgba(0, 0, 0, 0.5),0 6px 0 rgba(0, 0, 0, 0.5);
  line-height:150%;
  background: rgba(0, 0, 0, 0.5);
  color: #fff; 
  display: inline;
  box-decoration-break: clone;
  -webkit-box-decoration-break: clone;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM