Avoid Highlight Selection Overlap with CSS

Viewed 449

How can I avoid a highlight overlap when I select the text that has a line-height lower than the font-size?

Highlight overlap example image

Example:

*::selection {
  background-color: grey;
}

p {
  font-size: 24px;
  line-height: 20px;
}
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>

The only way I've been able to solve this is by making the background-color transparent and just changing the text color. I'd like to still have the background color though.

Example

*::selection {
  background-color: transparent;
  color: red;
}

p {
  font-size: 24px;
  line-height: 20px;
}
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>

3 Answers

I don't think there is a way, the selection background has to cover the whole alphabet, including all the special characters like ƒ, È, ¡, and so on.

Selection Example

I had exactly the same problem and it is quite relevant for the esthetics of a website. especially serif fonts come with a tall line height which is definitely too much if you use them for short text and greater font size. it's disappointing that there is no solution.

Why can you see the background of the selected text overlapping at all if the background color is not transparent? the browsers must apply an effect like multiplying.

And what does the text selection highlighting really depend on? it seems like it depends on the native line height of the font, which is, especially of some free web fonts, ridiculously high, let's say just wrong. But then there is no way to correct that.

Well, erm... no, not really.

This isn't really possible because the background covers all the text, so if the line height is under the size of the font size, there will be overlaps. However, you can sort of hide the background overlaps by setting the background to a slightly (and only very slightly) transparent background.

Something a bit like this:

*::selection {
    background-color: rgba(0, 125, 255, 0.99);
}

p {
    font-size: 24px;
    line-height: 20px;
}
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>

Related