JSFiddle - React, Tailwind, and code Playground
HTML
<p>This is a very long text that might wrap into multiple lines and it has a <span class="js-highlighted">wavy highlighted section which could span across several lines when the viewport is resized</span> or some other conditions change.</p>
<svg style="position: absolute; width: 0; height: 0;" xmlns="http://www.w3.org/2000/svg">
<filter id="wavyHighlight" x="0" y="0" width="100%" height="100%">
<feTurbulence type="fractalNoise" baseFrequency="0.02" numOctaves="2" result="noise" seed="1" />
<feDisplacementMap in="SourceGraphic" in2="noise" scale="7" />
</filter>
</svg>
CSS
.highlight-background {
position: absolute;
background: hsla(120, 60%, 50%, 0.3);
padding: 0.2em 0.2em;
transform: translate(-0.2em, -0.2em) skew(7deg, 0);
filter: url(#wavyHighlight);
z-index: -1;
}
JavaScript
function applyHighlights() {
const rects = Array.from(document.querySelector('.js-highlighted').getClientRects());
// Clear previous highlights
document.querySelectorAll('.highlight-background').forEach(e => e.remove());
rects.forEach(rect => {
const highlight = document.createElement('div');
highlight.classList.add('highlight-background');
highlight.style.top = rect.top + 'px';
highlight.style.left = rect.left + 'px';
highlight.style.width = rect.width + 'px';
highlight.style.height = rect.height + 'px';
document.body.appendChild(highlight);
});
}
window.addEventListener('load', applyHighlights);
window.addEventListener('resize', applyHighlights);