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:
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); }
Comments
David
Thanks for figuring out an IE solution! All the best from Austria – David
David
*(to whoever did it)
Tom
Doesn't work in firefox :-(
Geoff Muskett
What version of FF mate? I haven't seen any probs in reasonably recent versions...
Klinke
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
FF34+ can be fixed using box-decoration-break: clone;
Anonymous
helped me out thank you
Robert
Geoff, this is two years old and still relevant. Great post, I love the simplicity of the solution. Thanks!
Sybil
Brilliant!
Thank you!
Paul
Cheers for this neat and lightweight solution, thanks mate
CSSGURU
if you animate the h2 - the layout will break.
Andy
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.
Dominik
Thanks for this!
I modified your styles slightly. The `h2` element just defines the font size and remains a block element. Then the `span` gets styled like this:
```
box-shadow: 0 0 0 10px #fff;
background-color: #fff;
line-height: 2.4;
```
The fourth number of `box-shadow` indicates `grow`, which can be imagined as the shadow growth when moving the light source closer towards the object. The shadow in my example will created a visual padding of 10px. If you need more side padding, you can combine two shadows, where you move one to the right and the other to the left: `box-shadow: -7px 0 0 10px #fff, 7px 0 0 10px #fff;`. Note that this does only work with opaque colors.
@Andy Remove the `display: inline` from the `h2`.