I'm trying to create a highlighting effect which leaves a bit of space at the front and at the end for legibility, to mimic how you'd highlight a book. Here are a couple of attempts:
p {
width: 10em;
}
mark.with-padding {
border-radius: 10px;
padding: 0.4em 0.2em;
background-color: hsl(200deg 100% 80%);
box-decoration-break: clone;
}
mark.with-before-after {
border-radius: 10px;
padding: 0.4em 0px;
background-color: hsl(200deg 100% 80%);
box-decoration-break: clone;
}
mark.with-before-after::before {
content: '\2009';
}
mark.with-before-after::after {
content: '\2009';
}
<p>Some text here. <mark class="with-padding">This text is highlighted</mark></p>
<p>Some text here. <mark class="with-before-after">This text is also highlighted</mark></p>
- Using padding along with
box-decoration-break: clone;applies padding on soft line breaks too, which I like. However, the vertical alignment of text is understandably not quite right, because the padding takes up some space for lines which have highlighting at the start. - Using
::before+::afterwith a thin space ensures vertical alignment for lines which begin with highlighting vs without. However, this means that there is no gap between the highlight and the text on a new line.
With a physical book, the text is normally left-aligned and highlighting "overflows" outside of that boundary. So it's a mix of 1 + 2, you have both padding (depending on where you start highlighting) and vertical alignment.
How do you create such an effect with pure CSS (no JS)?
See below for an approximate example of the desired result, which I manually drew in Notability:
This has three properties:
- Line-wrapping works (like an
inlineelement). - The text is properly justified; the left edge of the text for the highlighted line ('t') matches the left edge of unhighlighted line ('p').
- There is "padding" on the highlights before and after the text, on every line.
The combination of these properties means that the highlight must "overflow" outside the left/right boundaries of the text content.
