Oct 13

Background color on inline element with padding

A tip I would like to throw out since many people seem to be searching for this. It’s a difficult problem, but here is a (rather dirty) way to use a background color on inline element (like span) and have padding as well. This is a solution when you want text with a background color plus padding – without filling the whole element block .

The problem

An inline element doesn’t begin new lines usually. If you ever tried you would see that padding will only apply to the begin and end of this element. If there are line-breaks it doesn’t look pretty.  This means limited styling options.

A block element does support padding but you can’t put the background on the text only.

Solution mostly

Most problems can be overcome by defining the inline element as a block level element ( or better just use a block element like <div> .

If you can control the output this way, you can put every line output on a different container. This often doesn’t fly with CMS-systems where the system outputs the whole ( as content ).

Better yet, punch the designer who thought of this.


In this specific case you want the best of both worlds and that often doesn’t fly with web design.

Fortunately there is a  Jquery plugin by Jeremy Harris which does this after your page loaded. This is important since often it’s not sure how many lines exactly your output will take (especially when the content is dynamic). The plugin splits the lines into seperate containers which you can use to style your padded background on.

This also works if you need to animate or do other tricky stuff with multi-line content.