Text with background, padding on the end of each line, and a gap between lines

By Geoff Muskett

Long descriptive title. Check. Seemingly simple problem thats actually quite awkward. Check.

The problem

The problem is you can’t just add padding and a background colour to the heading because it will only be applied to the beginning of the first line, and the end of the last line. Lines in between won’t have any padding. Like this:

text with background no spacing on middle lines

There are quite a few examples of achieving the desired effect, but without the gap between lines. Like wrapping text in a <span>, giving the span a background, then negative margin-ing the text pulling it into a one sided border.

Clever, but it won’t give you a gap. CSS tricks has a good rundown of solutions, the technique below is my favoured one. I’ve tested it down to IE8 and it works great.

The Solution

Box shadow to the rescue!

First, the HTML. Nest a <span> inside your heading.

<h2><span>Could you benefit from having Alfi in your home?</span></h2>

Then throw this CSS as it. Just make sure your line height is great enough to give that lovely gap.

h2 {
 line-height: 1.8em;
 font-size: 1.7em;
 display: inline;
 }

h2 span {
 padding: 0.2em;
 box-shadow: 0.2em 0 0 rgba(#fff,0.7), -0.2em 0 0 rgba(#fff,0.7);
 background-color: #fff;
 background-color: rgba(#fff,0.7);
 }

Ta daa

multi-line heading text with background and space between lines

Comments

David
March 17, 2014

Thanks for figuring out an IE solution! All the best from Austria – David

David
March 17, 2014

*(to whoever did it)

Tom
December 16, 2014

Doesn't work in firefox :-(

Geoff Muskett
December 20, 2014

What version of FF mate? I haven't seen any probs in reasonably recent versions...

Klinke
March 13, 2015

I came up with a fix based on this snippet. Tested in IE9+/Safari/Chrome/Firefox:
http://stackoverflow.com/questions/29032560/multiline-headline-w-background-color-in-firefox

Cheers!

Roel
March 27, 2015

FF34+ can be fixed using box-decoration-break: clone;

Anonymous
January 19, 2016

helped me out thank you

Robert
March 11, 2016

Geoff, this is two years old and still relevant. Great post, I love the simplicity of the solution. Thanks!

Sybil
March 26, 2016

Brilliant!

Thank you!

Paul
June 25, 2016

Cheers for this neat and lightweight solution, thanks mate

Andy
May 3, 2017

The example doesn't match the code. How did you get the text to align right? Putting text-align:right to either of the elements doesn't work.

Leave a Reply

Your email address will not be published.

Join my newsletter

If you’re looking for insights into web design and development, and crafting a successful presence online, then you should join the smart folk on on my newsletter. I discuss my thoughts on an issue relating to the web, then provide and teach effective solutions.