Multiline text background color with css disable characters
I have multiline text content (browser terminated, not delimited <br>
) in an HTML document and want to add background highlighting. My first attempt was to wrap the text I wanted to highlight in <span>
and create it accordingly:
/* part of CSS Reset */
body { line-height: 1; }
#highlight {
background-color: blue;
color: white;
}
<p>Lorem ipsum <span id="highlight">dolor sit amet, consectetur adipiscing elit. Donec sed ipsum ut nulla tempus sodales. Aliquam augue nisl, cursus nec volutpat in, sagittis</span> in mi.
This means the following:
Note that the bottom of the characters with descenders ('g', 'p', ',') are off, where they seem to overlap with the background of the next line.
I tried to fix this with a transparent background, but that only helped to better demonstrate the overlap:
/* part of CSS Reset */
body { line-height: 1; }
#highlight {
background-color: rgba(0, 0, 255, 0.5);
color: white;
}
<p>Lorem ipsum <span id="highlight">dolor sit amet, consectetur adipiscing elit. Donec sed ipsum ut nulla tempus sodales. Aliquam augue nisl, cursus nec volutpat in, sagittis</span> in mi.
Alternatively, magnification line-height
seems to work:
#highlight {
background-color: rgba(0, 0, 255, 0.5);
color: white;
line-height: 1.2em;
}
<p>Lorem ipsum <span id="highlight">dolor sit amet, consectetur adipiscing elit. Donec sed ipsum ut nulla tempus sodales. Aliquam augue nisl, cursus nec volutpat in, sagittis</span> in mi.
However, I need a way to fix this overlap issue without visually increasing the line spacing.
source to share
The fix I found was to wrap the text in the second <span>
and style that s position: relative
. The outer range displays the background color at the same position, and then the inner range displays text on top of it.
/* part of CSS Reset */
body { line-height: 1; }
#highlight {
background-color: blue;
}
#highlight > span {
position: relative;
color: white;
}
<p>Lorem ipsum <span id="highlight"><span>dolor sit amet, consectetur adipiscing elit. Donec sed ipsum ut nulla tempus sodales. Aliquam augue nisl, cursus nec volutpat in, sagittis</span></span> in mi.
source to share