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

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

CSS Magic #3. Обводка для текста (text-stroke effect)

Итак, обводка для текста на css в целом несложно делается, однако прежде чем начнем — стоит понимать, что данный метод не сработает в IE. Если Вам не особо нужен IE — либо игнорим проблему, либо выкручиваемся (я покажу как это можно сделать). Поехали!

Самая обыкновенная разметка. Даже и останавливаться на ней неохота, разве что тут два текста, один будет под IE, другой — под все остальное.

Используем два -webkit-свойства -webkit-text-stroke и -webkit-text-fill-color для достижения нужного результата. Текст будет прозрачным и будет иметь красивую, нужную нам, обводку. Под IE идем другим путем — придется задать цвет тексту и text-shadow . Конкретно такой код может не сработать, поэтому вот вам генератор тени для текста.

Определять браузер можно любым доступным способом (благо их полно в интернете), но если нужно — я расскажу в отдельной статье как)

И по традиции пен:

Вот собственно и все. Простой, но полезный эффект. К сожалению, не лишенный недостатков, но ничего в мире не бывает идеально.

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

От автора: CSS3 развивается таким образом, что мы можем перевести в код CSS почти все, что создается в Photoshop’е. Тем не менее, до сих пор нам не удавалась обводка текста (text-stroke). Можно было добавлять к тексту тени, но до настоящего момента не существовало жизнеспособного решения проблемы обводки. Сейчас в webkit появился ответ на этот вопрос, представляющий обводку текста с помощью одного лишь CSS.

Браузерная поддержка

Это свойство пока экспериментальное и не является безопасным для всех браузеров, но можно установить некие свойства по умолчанию, которые станут срабатывать лишь при применении пользователем неподдерживающего это свойство браузера (имеются в виду Firefox и IE). Важно понимать, что text-stroke – это не прогрессивное улучшение, вам потребуется резервный вариант для неподдерживающих браузеров, и ниже я раскрою вам существующее, к счастью, решение этой проблемы. Кроме того, в настоящее время text-stroke не фигурирует в спецификациях W3C, оно было наскоро включено под названием text-outline, но вскоре удалено и до сих пор заново не добавлено.

Свойство

Это – на самом деле очень простое в применении свойство, немного похожее на свойство border, да и пишется почти так же. Для назначения обводки текста потребуются лишь text-stroke-color и text-stroke-width с нужными вам значениями: например, если для всех тэгов-ссылок требуется черная обводка шириной в 2 пикселя, то вы напишете:

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:

Ссылка на основную публикацию