How do I set a background-color for the width of text, not the width of the entire element, using only CSS?
Anchor the background color by enclosing your text in a <span>
and setting the background-color
CSS property to it:
The <span>
tag behaves like a chameleon in the jungle – it adapts to the surroundings by behaving as an inline
element, delivering a color specific to the text it wraps, not the whole branch (element).
Fitting Background to Text
Use the display: inline-block
CSS property for a background that fits around the text as a glove fits around a hand:
Effortlessly paint a consistent background across multiline text using box-decoration-break: clone
:
Fair warning though, box-decoration-break
has an ongoing love affair with Firefox!
Adding background with CSS Pseudo-elements
For a no-fuss background addition without tweaking your HTML, think of ::before
as your fairy godmother:
But remember, it's not a glass slipper! Set the parent element's position to relative to contain the pseudo-element.
Prioritising Browser Compatibility and Accessibility
To dress your content in IE11-compatible attire, use outline
with a zero-width box-shadow
:
Techniques to set background to width of text
To create that perfect all-around space for the text, play around with adjustments to line-height
or add box-shadow
. Sample:
Flexbox is to CSS what yoga 🧘♂️ is to our bodies – all about flexibility and balance!
Ever tried target shooting? Use text-align: center
to center text within a display: inline
style setting:
Was this article helpful?