0

I'd like to display multiple lines of text with a semitransparent background. When these lines are too far away from each other, there's a gap in the background. When they're too close, the background overlaps and transparency is reduced. The background should be one homogeneous area of the same colour and transparency level.

Unfortunately, browsers and fonts are all different and I can't find one correct value to be set for the line-height that works for all situations. Subpixel positioning adds to it in that the gaps and overlaps change with the exact window or element size.

Here's the sample code:

.bg1
{
  background: khaki;
  padding: 20px;
  font-size: 1.3em;
  line-height: 1.1;
}
.bg2
{
  margin-top: 1em;
  background: khaki;
  padding: 20px;
  font-size: 1.3em;
  line-height: 1.5;
}
.text
{
  background: rgba(255, 69, 0, 0.5);
  padding: 2px 8px;
  box-decoration-break: clone;
  -webkit-box-decoration-break: clone;
}
<div class="bg1">
  <span class="text">
    Line 1<br>
    Second line<br>
    Text background overlapping
  </span>
</div>
<div class="bg2">
  <span class="text">
    Line 1<br>
    Second line<br>
    Gaps between text lines
  </span>
</div>

Line height values in the sample are exaggerated and an example to increase the chance that you see the intended result. Multiple lines are enforced with <br> here, but wrapping can also occur in my usage, i.e. manually spreading the lines over separate block elements is not a solution. It has to be inline content.

What value can I use for line-height to ensure that the text lines exactly touch each other with no overlap or gaps?

I can't accept line-height: normal for reasons explained here and because I need additional inner padding on the text lines, as shown in the example.

ygoe
  • 18,655
  • 23
  • 113
  • 210
  • After more reading, also [this question](https://stackoverflow.com/q/61830546/143684) and more linked questions in there, I get the impression that CSS is plain incapable of allowing such layouts because it explicitly does not want to specify the actual dimensions of text height. Looks like a major design flaw of CSS. – ygoe Jun 07 '20 at 13:58
  • I tried to fix this up with some measuring in JavaScript, but `getBoundingClientRect` doesn't provide accurate data. It was off by ~0.5 px in my case. Also it would fail when text is restyled e.g. with responsive design (`@media`) because the real text height to font size ratio changes with font size (and style and family, but I already observed that; maybe also UA and screen pixel density, didn't try that). – ygoe Jun 07 '20 at 14:04

0 Answers0