How to Add Text Outline with CSS

Introduction

Adding an outline to text in CSS helps make it stand out by creating a border-like effect around the characters. While there isn't a direct property for text outlines, you can achieve this effect using the text-shadow property to simulate an outline.

In this tutorial, you'll learn how to create a text outline using the text-shadow property in CSS.

Problem Statement

Create a CSS code that:

  • Adds an outline to text by applying multiple shadows using the text-shadow property.
  • Demonstrates how to simulate a text outline with different colors and thicknesses.

Example:

  • Input: A heading element with the text "Text Outline Example".
  • Output: The text appears with an outline around the characters.

Solution Steps

  1. Use text-shadow to Simulate an Outline: Apply multiple shadows around the text to create the illusion of an outline.
  2. Adjust Shadow Offset and Color: Control the shadow’s spread and color to define the thickness and appearance of the outline.

HTML Structure

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Text Outline Example</title>
    <style>
        /* Step 1: Add text outline using text-shadow */
        .outlined-text {
            font-size: 3rem;
            color: white;
            text-shadow: 
                -2px -2px 0 black,
                 2px -2px 0 black,
                -2px  2px 0 black,
                 2px  2px 0 black;
        }
    </style>
</head>
<body>

    <h1 class="outlined-text">Text Outline Example</h1>

</body>
</html>

Explanation

Step 1: Use text-shadow to Simulate an Outline

  • To create an outline effect around the text, use this CSS:

    .outlined-text {
        font-size: 3rem;
        color: white;
        text-shadow: 
            -2px -2px 0 black,
             2px -2px 0 black,
            -2px  2px 0 black,
             2px  2px 0 black;
    }
    
  • The text-shadow property creates multiple shadows at different offsets (-2px, 2px), making it appear as an outline around the text.

  • The color property is set to white to highlight the contrast between the text and the outline.

Output

How to Add Text Outline with CSS

Conclusion

Adding an outline to text in CSS can be achieved using the text-shadow property. By adjusting the shadow offsets and colors, you can create a clean outline effect around your text, making it stand out in your design.

Comments