Search code examples
htmlcsspaddinghighlight

How to include padding on a span element that has multiple lines


jsfiddle here.

I have a span element that is highlighted using background-color: yellow and padding: 1px 10px.

normal here

However, on smaller devices, this line of text becomes two lines, three lines, etc. This causes the first and second lines to 'lose' the padding on the right side, such as the words "the" and "to", and the second and third lines to 'lose' the padding on the left side, such as the words "highlight" and "better" in the picture below:

the problem

How can I ensure these words (in the picture above, "the", "highlight", "to", "better") and all other words keep this 10px padding on the left and right side?

Someone in response to a similar question suggested using display: block, but this makes the span no longer a span, just a rectangle and that is not how I need it to look. It also makes the highlight span the entire width of the page.

undesired result


Solution

  • You can try faking the background when the span is broken by using box-shadow. Try something like this and see if it works for you:

    span {
        background-color: yellow;
        padding: 1px 0;
        box-shadow: 10px 0 0 0 yellow, -10px 0 0 0 yellow;
    }
    <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam a nisi ipsum. Mauris convallis dapibus diam ac sollicitudin. Vivamus varius nulla magna, ac rutrum nulla accumsan quis. Duis placerat, elit non posuere elementum, tellus massa pellentesque nunc, eu maximus ligula metus non dui. Sed accumsan quam nec sodales sagittis.</span>