askvity

How do you add text to an outline color in HTML?

Published in HTML & CSS 2 mins read

You can add an outline color to text in HTML using the non-standard -webkit-text-stroke property.

Using -webkit-text-stroke

The -webkit-text-stroke property is used to apply a stroke (outline) to text. Because it's prefixed with -webkit-, it primarily works in WebKit-based browsers (Chrome, Safari, and others).

Syntax

The basic syntax is:

-webkit-text-stroke: [width] [color];
  • width: The width of the outline. Use CSS units like px, em, or rem.
  • color: The color of the outline. Use any valid CSS color value (e.g., red, #FF0000, rgb(255, 0, 0)).

Example

<!DOCTYPE html>
<html>
<head>
<title>Text Outline Example</title>
<style>
.outlined-text {
  -webkit-text-stroke: 2px blue; /* 2px blue outline */
  color: white; /* Text color */
  font-size: 3em;
  font-weight: bold;
}
</style>
</head>
<body>

<p class="outlined-text">Outlined Text</p>

</body>
</html>

In this example:

  • The class outlined-text is applied to a <p> element.
  • -webkit-text-stroke: 2px blue; adds a 2-pixel wide, blue outline to the text.
  • color: white; sets the fill color of the text to white, making the outline clearly visible. Changing this will change the color inside the stroke.
  • font-size and font-weight are added for emphasis.

Browser Compatibility

Keep in mind that -webkit-text-stroke is not a standard CSS property. While it works well in WebKit-based browsers, its support in other browsers (like Firefox or Internet Explorer/Edge) is limited. There is no standard, cross-browser CSS property to achieve exactly this effect, though other techniques (like using text-shadow to simulate an outline) can provide similar results.

Alternative Approaches (Text Shadow)

Since -webkit-text-stroke is non-standard, a more cross-browser compatible approach (though not exactly the same) is to use the text-shadow property.

.outlined-text-shadow {
  color: white; /*  Inner text color */
  font-size: 3em;
  font-weight: bold;
  text-shadow:
    -1px -1px 0 #000, /* Top left */
    1px -1px 0 #000, /* Top right */
    -1px 1px 0 #000, /* Bottom left */
    1px 1px 0 #000; /* Bottom right */
}

This creates a faux-outline by applying shadows to all four sides of the text. Adjust the color and pixel values as needed. You can add more shadows for a thicker stroke.

In summary, using -webkit-text-stroke provides a true text outline, but relies on browser-specific support. Using text-shadow offers broader compatibility, although the result is an approximation of a true outline.

Related Articles