Back to blog

TIL: Adding text borders with CSS

After checking my website on mobile, I realised that I'd made a mistake, and included a pretty bad colour contrast issue on the page:

Screenshot of a blog post showing white text unreadable against a multicoloured background

So I took to Google, and discovered that I could use the -webkit-text-stoke CSS property (MDN Documentation), which will add a border to the characters. It's well-supported, despite using the -webkit prefix:

.text {
    color: white;
    -webkit-text-stroke: 1px black;
}

This worked, but because the stroke goes on the inside of the text, rather than the outside, the result is much harder to read and doesn't look great.

Screenshot of a blog heading, but the text has a black stroke to it, making the letters appear smaller and distorted, but readable against the background

So I took to Google again, and found a StackOverflow answer that gave me a really useful snippet, using text-shadow:

.text {
    color: white;
    text-shadow: -2px -2px 0 #000,
    0   -2px 0 #000,
    2px -2px 0 #000,
    2px  0   0 #000,
    2px  2px 0 #000,
    0    2px 0 #000,
    -2px  2px 0 #000,
    -2px  0   0 #000; 
}

This is a much better result - it produces a nice 2px border around the text, which makes it easier to read against bright backgrounds, but doesn't impact the legibility of the individual characters.

Screenshot of the heading. Text that goes across brightly-coloured background has a black outline, making it stand out more.

2 responses to “TIL: Adding text borders with CSS”

Reposts

  • Abbie :verified: