Как сделать контур текста в html
Перейти к содержимому

Как сделать контур текста в html

  • автор:

Текстовые эффекты

В посте представлены некоторые эффекты на основе text-shadow .

text-shadow — это свойство, описывающее тень, отбрасываемую текстом. В отличие от box-shadow , тень не обрезается фигурой, ей нельзя задать размер (только радиус размытия) и она не поддерживает параметр inset , то есть нельзя сделать внутреннюю тень.

Тем не менее, используя несколько теней с различными параметрами можно сделать имитацию обводки (которую было бы проще получить, если бы тень поддерживала размер) и имитацию внутренней тени, что позволяет сделать вдавленный текст.

Сочетая тени, градиенты и псевдо-элементы можно сделать много интересного.

Проведите курсором над текстом примеров, чтобы увидеть эффекты при наведении.

CSS Text Outline Everything About Stroke Text In CSS

In this tutorial I will show you how to create the stroke text CSS effect.

Before we go into the HTML and CSS code, if you only need to create a stroke text image, check out this tutorial and learn how to outline text in Photoshop.

Or, if you don’t have Photoshop, you can use the free online tool MockoFun which even has a dedicated stroke text tutorial.

Text With Border

Add Stroke To Text Using CSS -webkit-text-stroke

Stroke Text CSS

As an example, let’s add a black stroke to a text. I will start with some HTML code:

Exit fullscreen mode

And the CSS code:

Exit fullscreen mode

Pretty straight forward, we make the text transparent – though this is not necessary, but I only want to the outline of the text to be visible and not the body of the letters. Then, the -webkit-text-stroke property adds a black outline stroke 5px thick. You can change this to get thicker outline text or a thinner outline, depending on what effect you want to obtain.

You can use this to stroke text in CSS on all Webkit based browsers (like Chrome or Edge) and Firefox too.

This is a non-standard feature, so not something you can rely 100%.

It’s not supported on all browsers and according to CanIUse.com: this property does not yet appear in any W3C specification. Was briefly included in a spec as the text-outline property, but this was removed.

Just to give you a hint of what you can create with this text stroke CSS property, here’s my Cyber Space text effect part of the 80s fonts text effects gallery.

Stroke Text 80s Fonts Effect

Adding Stroke To Text Using text-shadow

Another method to outline text in CSS is by using shadows. CSS allows adding multiple shadows to a text element via the property text-shadow .

So, let’s make a white on white text and add 4 red shadows to it. Offset the 4 shadows by 1px up, left, down and right. Here’s the HTML code:

Exit fullscreen mode

and the CSS code:

Exit fullscreen mode

Here’s a graphical representation of what’s going on and how the CSS text stroke effect is achieved using text shadows:

Stroke Text CSS Shadow

Perfect, isn’t it?

Well, not exactly, but pretty damn good. Let’s point out some draw backs and solutions for it.

First, if we need to modify the text outline thickness or color we need to change it in multiple places, and this can be tedious.

CSS offers us quite an elegant solution which I use quite often for convenience and that is CSS variables. You can read more about CSS variable here, but what you need to know is that if you in your CSS you have to repeat values over and over again, CSS variables are a tremendous help.

Using CSS Variables To Configure The Text Stroke Color And Thickness

Basically you define a CSS variable like this: —my-variable:value . Then, throughout your CSS code if you need that value simply use property:var(—my-variable);

So, change the CSS code above like this:

Exit fullscreen mode

The —stroke-color variable stores the color for the text stroke and —stroke-width stores the width of the stroke. Then in the text shadow we use those variables. This allows making changes only in one place if we were to modify the color or the width of the text stroke.

Pretty neat, isn’t it?

In the text-shadow property, I’ve made use of the CSS calc function to allow me to multiply the text stroke width by -1 for the up and left shadow directions.

If you start playing around with this and change the thickness of the text stroke you will notice that for larger values, something is wrong at the corner of the letters.

And so we come to our second draw back:

CSS Stroke Text

We see some breaks in the text stroke because we are only using 4 shadows that we shift on 4 directions.

So, what should we do to fix this?

The answer is simple: add more shadows!

Hang on to your hats kids and take out your math notebooks. This is a “Definitive Guide to Stroke Text” after all, so we need to be thorough.

If we add more shadows to our text, we need to figure out how to shift those shadows around our text to cover all the gaps in the text outline. Intuition says that we should spread them evenly on a circle with a radius equal to the width of the text stroke.

And, intuition is right!

To calculate the offsets of the shadows we use the polar coordinates formulas:

Exit fullscreen mode

Where x and y are the offset values, r is the radius of the circle (actual amount that we want to offset by which translates into the thickness of the text stroke) and alpha is the angle by which we want to divide the circle into.

We can assign values to alpha depending on how many shadows we want to add to create our text stroke.

For example, for 8 shadows we divide 2*PI (the full circle) by 8 and we get an angle of PI/4. Then if we assign values to alpha with a step of PI/4 like 0, PI/4, PI/2, … until we complete the circle, we should get our 8 shadows offsets perfectly aligned on a circle.

CSS Stroke Text

The more shadows we add, the smoother the CSS text stroke becomes for larger values of the stroke width. There are no trigonometric function in CSS yet, so we need to calculate the values ourselves.

Let’s modify the HTML and CSS code to add a smooth text stroke with 16 shadows:

Exit fullscreen mode

and add the CSS for the smooth text stroke:

Exit fullscreen mode

For convenience, I’ve created a JS function that generates the stroke text CSS code depending on how many shadows you want to have. Here’s the code:

Exit fullscreen mode

Run this function with steps=16 and you will get the CSS value for the text-shadow property. Please note that this JS code does not have to be part of the page where you display the CSS stroke text. Here’s the Codepen snippet with where you can play with the code:

Now we have two perfectly valid methods for creating CSS stroke text, but since this is a definitive guide I will not stop here and I will show you a couple of extra alternatives for creating a text outline with CSS shadows.

QUICK TIP: This exact same method works for creating outline images from PNG images for example.

Add Stroke To Text Using CSS SVG Filters

If you don’t know about SVG filters or what you can do with them I strongly suggest you read this article about 80s fonts and SVG filter text retro effects. WARNING: prepare to be amazed ��

Basically, you can define SVG filters that you can then use in CSS with the filter property. In one of my recent articles I’ve made heavy use of CSS filters to create CSS image effects. But, in our case we will use SVG / CSS filters to add stroke to a text.

Here’s the HTML code along with the SVG filter definition:

Exit fullscreen mode

and the CSS code:

Exit fullscreen mode

which renders a blue outlined text like this:

Stroke Text SVG

So, how does this work?

Well, the stroke-text-svg-filter SVG filter we apply to our text has two steps:

  • feMorphology with dilate takes the original text and “dilates” or enlarges the text in all directions by a radius of 2 pixels
  • feComposite with the operator=»xor» performs a XOR operation which actually subtracts from the enlarged text the original text, such that we are left with a hollow text or outlined text

Change the thickness of the text stroke you have to modify the radius attribute in the SVG filter. To change the color of the text stroke, simply change the color CSS property in the stroke-text class.

This SVG filter also works for PNG images.

The only downside for this method of adding stroke to text is that the end result looks a bit coarse for bigger values of the radius . This is because the dilation algorithm tries to expand the letters in all directions which means that it might not render a true outline which should be equally sized in all directions.

Here’s the Codepen for adding stroke to text with SVG filters:

** Note: ** just like in the example above, in the text you can use a heart or arrow symbol. You could actually use any emoji or text symbol you like (see more text symbols).

SVG Text Outline

Besides SVG filters, we can create the text outline using SVG text and CSS specific for SVG.

Though not exactly an HTML and CSS only solution, this solution probably creates the best looking text outline effect.

SVG Stroke Text

To create a text outline with SVG and CSS here’s the SVG code that you add in your HTML page:

CSS Text Stroke/Outline

Example of CSS Text Stroke/Outline

Developing content for the web, you may come across the requirement of adding an outline to the text. This article will demonstrate different possibilities for creating text outlines via CSS and their limitations.

Let’s start with the text-shadow property. You may be tempted to think that a plain text-shadow should fulfill our requirement but that is not the case. While it tries to provide a good approximation, the browser has to render the text multiple times and it is not perfect at corners. Let’s see it in action.

Using 4 Text Shadows

Let’s create a text and add 4 text shadows to it, one for each direction.

Zooming in on the result, you can see the corners are not filled in and some curves lack the outline.

Using 8 Box Shadows

We can improve the results by adding diagonal shadows to fill in the corners. The «1.41» values are there to make the diagonal shadows the correct distance. This value is easy to calculate with the following formula: √(R² ÷ 2) (where R is the radius of the stroke). To put it more simply, take the desired stroke width (in this case 2), multiply it by itself (2 × 2 = 4), divide that by 2 (4 ÷ 2 = 2), and then take the square root (√ 2 = 1.41).

This required the browser to render the text 9 times. The shadows are improved but still not perfect. If you zoom into the corners, you can still observe steps at the corners.

This technique performs particularly poorly in the case of thicker strokes. The diagonal stroke distances have been calculated in the same way: √(9² ÷ 2) = 6.36

Using -webkit-text-stroke Property

CSS offers a dedicated property named webkit-text-stroke which is capable of applying perfect text outline.

This property has fairly good support across browsers. But to be on the safe side, we can use the text-shadow as a fallback, and only use the -webkit-text-stroke if the browser supports it.

This will render the perfect outline on browsers that support it, and the fallback text-shadow outline on browsers that do not.

Zomming-in on the corners, you can observe there are no steps or missed curves — if. your browser supports text-stroke property.

Using SVG Filters

SVG filters are a very handy tool for visually modifying content. There are many filters offered out of the box with flexible, customizable properties. You can apply the filters step-by-step and monitor the output of each. SVG Filters enable theoretically infinite possible effects for the text.

For this article, we will build two outline filters step by step. The first one will build an outline that supports black color only while the second one will be able to draw an outline of any color of your choice.

Note: SVG filter does not quite provide an even stroke all the way around the text. It also does not have any better browser support than -webkit-text-stroke , making the -webkit-text-stroke the best option for most websites, with the text-shadow fallback.

Black Outline

Let’s build the first filter. We can create an outline by taking the text’s alpha-channel/opacity (visually exact text but black colored only as all the other colors are dropped), increasing its thickness (dilating it), and placing the original text on top of it.

We render the original text.

We define the boilerplate of the filter.

Step 1: Take the source alpha only of the text input using the feMorphology filter.

Note that we are adding code to the original boilerplate step by step, and not defining a new filter.

Step 2: Dilate (make bigger) the result of source alpha. We will dilate it with a radius of 2. This dilution will become the thickness of the outline. You can adjust the value as per your need.

Step 3: Merge the dilated text and the original text. Original text will be placed on top of the alpha. This is the last step and the end visual result will be our text with an outline. We have the final code of the filter and its visual output.

You can now use this filter on the text (or any other element) to get a black outline, with a thickness of your choice. Applying the filter requires only setting the element’s filter attribute in CSS.

Note: If you need to put the definition of your SVG Filters in the markup of your page without them showing up as text (just like for this article), make sure you wrap them in an absolutely positioned <div> having a width and height of 0 pixels. You may be tempted to wrap in a <div> with display set to none but the filter stops working in that case.

Colored Outline

The step-by-step process behind the second filter will be as follows

  • Create a replica of text with increased/dilated thickness
  • Create a solid rectangle with the color of your choice
  • Compose the text and rectangle together so that only the overlapping pixels of the rectangle are extracted as output. This will essentially complete the process of creating a colored outline
  • Merge the text and colored outline into one. The result will be the original text with an outline of the selected color

Let’s build the second filter — one that supports any color for the outline. Here is our original text

We define the boilerplate of the filter.

Step 1: Add an feMorphology filter that takes the source alpha channel (opacity) of the input and dilates it with a radius of 2. This will create a replica of text but with increased thickness. The result is stored in “Dilated”.

Step 2: Add an feFlood filter to create a solid rectangle. We provide our selected color as a hexcode with the input named flood-color. The result gets stored in “OutlineColor”.

Step 3: Compose the source alpha and the rectangle together using feComposite filter. The feComposite filter uses the «in» operation, which takes each pixel from the «in» attribute. If it overlaps a pixel in the «in2» attribute, then the pixel from «in» is used. Since we have just used the alpha channel in feMorphology, this essentially turns the «in2» attribute into a mask for the «in» attribute, effectively creating a larger version of our original text in a solid color of our choice. This gets stored in «Outline».

Step 4: Merge the outline and the text. After composing the solid rectangle with our outline mask, we have our colored outline. The last step is to merge the outline and text together using feMerge filter.

Now we can apply it to our element using CSS.

Here is the complete codepen.

Examples

A fancy, multi-line stroke

See the Pen text stroke by Freddy Gomez (@dajama) on CodePen.

Stroked text with decoration

Gradient text stroke

A fancy mill using text stroke and animation

A very subtle text stroke with a background image

UnusedCSS helps website owners remove their unused CSS every day. Sign Up to see how much you could remove.

Как сделать обводку текста в CSS?

Тень текста CSS

Приветствую вас, дорогие посетители сайта Impuls-Web!

Сегодня я хотела бы продолжить тему форматирования и показать, как можно сделать обводку текста CSS.

Навигация по статье:

Обводка теста css-свойством text-shadow

Для того, что бы придать эффект обводки мы можем использовать css-свойство text-shadow для задания тени тексту.

По заданию параметров, данное свойство очень похоже на box-shadow и имеет следующий вид:

Эксперимент с тенью

Так же, как и в случае с тенью для блока, если нам нужна обводка текста css по контуру, то нам нужно задать тень четыре раза.

Вот как это будет выглядеть:

Обводка текста в CSS

В принципе, ни чего сложного. Если понять закономерность и немного поэкспериментировать, то у вас обязательно получиться добиться нужного вам результата.

Онлайн-генератор теней

Если же вам не хочется заморачиваться или вы постоянно путаетесь в параметрах свойства, то вы можете воспользоваться специальным генератором обводки текста на CSS3.

Здесь все просто:

  1. 1. Переходите на страницу сервиса
  2. 2. Рабочая область поделена на две части. В левой части вам нужно задать параметры для текста, а в правой вы можете посмотреть, что в результате получится.

Обводка текста CSS

Настройка генератора обводки

Надеюсь, показанные мой в этой статье инструменты, помогут вам сделать для своего сайта красивую обводку текста CSS. Не забывайте делиться статьей в социальных сетях, и обязательно подписывайтесь на мою рассылку новостей.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *