Set Font Border in CSS

  1. Use the -webkit-text-stroke Property to Apply Borders to Font in CSS
  2. Use the text-shadow Property to Apply Borders to Font in CSS

This tutorial will introduce methods to apply border and color to the font in CSS.

Use the -webkit-text-stroke Property to Apply Borders to Font in CSS

We can use the text-stroke property on a text to apply borders to a font in CSS. We need to use the webkit prefix ahead of the text-stroke property to use the feature. However, it only works on the web-kit based browsers like Safari and Chrome. The text-stroke property lets us decorate the text in vector drawing applications like Adobe Illustrator. The property is the shorthand of the other two properties, text-stroke-width and text-stroke-color. Thus, we can define the width and color of a text’s border with text-stroke property.

For example, write some text inside the h1 tag in HTML. In CSS, select the h1 tag and apply the -webkit-text-stroke property. Set the width to 1px and color to red. Then, set the font to arial using the font-family property and give the green color.

The example below will display a green-colored text which has a border of red color. This is how we can set borders in a font with a different color.

Example Code:

<h1>The green font has red border</h1>
h1 {
 -webkit-text-stroke: 1px red;
 font-family: arial; color: green;
}

Use the text-shadow Property to Apply Borders to Font in CSS

We can emulate the text-stroke property using the text-shadow property to apply a border to the font in CSS. The text-shadow property is used to create a shadow to a text. The first two values denote the h-shadow and v-shadow properties. They denote the position of horizontal and vertical shadow. We can set the blur-radius value as the third value in the text-shadow property. It will blur the shadow from the given position with the given radius. We can specify the colour of the shadow, making it the fourth value in the text-shadow property. This method works on most browsers.

For example, write some text inside the h1 tag in HTML. In CSS, select the h1 tag and write the property text-shadow. Give the value 0 for both the h-shadow and v-shadow properties. Write 2px for blur-radius and give the red color.

We emulated the border feature on a font using the text-shadow property in the example below. We set the value 0 for horizontal and vertical radius so that the shadow looks like a border when giving the color to the shadow.

Example Code:

<h1>The black font has red border</h1>
h1 {
 text-shadow: 0 0 2px red;
}
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.