Multi-Line Padded Text With Background and Line Spacing

Update May 2017: Matt Brunt pointed me to a lovely hack using box-shadow which you should probably totally use instead of the 2-year-old method below.

I've been working on a project that called for some text to be wrapped on to multiple lines with a background behind it. We didn't know the precise number of lines the text would be as the client would be managing from a CMS. The fact that it was responsive also made things a little trickier.

Example of what we were looking for

Chris over at CSS Tricks wrote an awesome article on how to achieve this. However, none of the techniques allowed for the gap between the lines as the majority used a left border to tidy things up.

The Solution

After some head scratching and a Twitter cry for help I wrapped each word in a span and positioned this appropriately in CSS (the lovely Mike Francis had the same idea 👍). As this was coming from WordPress, I just exploded the words and wrapped them in spans.

<?php

function getSpans($input)
{
    $pieces = explode(' ', $input);
    $wrapped = array_map(function($i){
        return '<span>'.$i.' </span>';
    }, $pieces);

    return implode('', $wrapped);
}

echo getSpans('Hello, how are you?');

// Returns "<span>Hello, </span><span>how </span><span>are </span><span>you </span>"

The space inside the span is important or when you copy the text you'll end up with everything bunched together. Might not seem like an issue but what if you were using a screen reader?==

The CSS is pretty simple, just chuck a background on the spans and pad them. Tweaking the line-height will increase or decrease the gap between the lines. The final thing I did was add a negative value to the word-spacing property to account for the padding we added so it didn't look so strange.

And that's it! You can see the result in the pen below.

See the Pen LEgEYV by Stephen Radford (@steve228uk) on CodePen.

Work With Us! We're currently accepting new projects at Cocoon. If you have a cool new thing you want us to help with, feel free to drop me a line ✌️

About Stephen Radford

Software Engineer. I take a few photos when I'm not stuck behind a keyboard too.

Leicester, UK http://stephenradford.co.uk

Comments