Read more

CSS: Giving text lines a background-color (with configurable line padding and margin)

Dominik Schöler
November 24, 2017Software engineer at makandra GmbH

The gist is:

  • wrap the text with a span
  • use line-height for the spacing between lines ("margin")
  • use box-shadow to control the line background size ("padding")

Example

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

text_lines_with_background_color.png

span
  box-shadow: 0 0 0 10px #fff
  background-color: #fff
  box-decoration-break: clone # Fix Firefox
  line-height: 2.2

jsfiddle Show archive.org snapshot

The fourth number of box-shadow indicates spread, which can be imagined as the shadow growth when moving the light source closer towards the object. The shadow in my example creates a visual padding of 10px.

Custom Padding

You can combine multiple shadows, moving each where you need the padding. Example with 7px extra padding left and right:

box-shadow: -7px 0 0 10px #fff, 7px 0 0 10px #fff

Note that this does only work with opaque colors.


Thanks to Geoff Muskett for the inspiration.

Posted by Dominik Schöler to makandra dev (2017-11-24 08:49)