Explain Codes LogoExplain Codes Logo

How do I set a background-color for the width of text, not the width of the entire element, using only CSS?

html
responsive-design
css
best-practices
Nikita BarsukovbyNikita Barsukov·Sep 30, 2024
TLDR

Anchor the background color by enclosing your text in a <span> and setting the background-color CSS property to it:

<p>Regular text <span style="background-color: #FFFF00;">highlighted text</span>.</p>

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:

/* Dressing the text up for a sunny day */ .highlight { background-color: #FFFF00; display: inline-block; }

Effortlessly paint a consistent background across multiline text using box-decoration-break: clone:

/* Paint the town, er... text, yellow! */ .multiline-highlight { background-color: #FFFF00; display: inline; 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:

/* Create a sunny day out of nowhere! */ .highlight::before { content: ''; background-color: #FFFF00; position: absolute; z-index: -1; top: 0; left: 0; width: 100%; height: 100%; }

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:

/* Let's time-travel to the IE11 era */ .compatible-highlight { color: black; background-color: #FFFF00; outline: 0px solid transparent; box-shadow: 0 0 0 3px #FFFF00; }

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:

/* Because every text deserves personal 🛀 space */ .shadow-spacing { background-color: #FFFF00; box-shadow: 10px 0 0 #FFFF00, -10px 0 0 #FFFF00; line-height: 1.5; }

Flexbox is to CSS what yoga 🧘‍♂️ is to our bodies – all about flexibility and balance!

/* Conjure a yellow spotlight in the center 🎭 */ .flex-center-highlight { display: flex; justify-content: center; background-color: #FFFF00; }

Ever tried target shooting? Use text-align: center to center text within a display: inline style setting:

<!-- Bulls-eye! 🎯 --> <div style="text-align: center;"> <span style="background-color: #FFFF00; display: inline;">Centered Text</span> </div>