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

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

  • автор:

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

Тень текста CSS

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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:

Outline effect to text

Are there any ways in CSS to give outlines to text with different colors ? I want to highlight some parts of my text to make it more intuitive — like the names, links, etc. Changing the link colors etc. are common nowadays, so I want something new.

17 Answers 17

There is an experimental webkit property called text-stroke in CSS3, I’ve been trying to get this to work for some time but have been unsuccessful so far.

What I have done instead is used the already supported text-shadow property (supported in Chrome, Firefox, Opera, and IE 9 I believe).

Use four shadows to simulate a stroked text:

I have made a demo for you here

And a hovered example is available here

As Jason C has mentioned in the comments, the text-shadow CSS property is now supported by all major browsers, with the exception of Opera Mini. Where this solution will work for backwards compatibility (not really an issue regarding browsers that auto-update) I believe the text-stroke CSS should be used.

vdegenne's user avatar

Kyle's user avatar

Easy! SVG to the rescue.

This is a simplified method:

CSS-only:

If you want a thick stroke, please read my other Stackoverflow answer

�� Note that as of writing, the -webkit-text-stroke property cannot be transitioned/animated.

Edit: text-stroke is now fairly mature and implemented in most browsers. It is easier, sharper and more precise. If your browser audience can support it, you should now use text-stroke first, instead of text-shadow .

You can and should do this with just the text-shadow effect without any offsets:

Why? When you offset multiple shadow effects, you’ll begin to notice ungainly, jagged corners: Shadow effect offsets result in noticeable jagged corners.

Having text-shadow effects in just one position eliminates the offsets, meaning If you feel that’s too thin and would prefer a darker outline instead, no problem — you can repeat the same effect (keeping the same position and blur), several times. Like so:

Here’s a sample of just one effect (top), and the same effect repeated 14 times (bottom):

Sample text rendered with text-shadow

Also note: Because the lines become so thin, it’s a very good idea to turn off sub-pixel rendering using
-webkit-font-smoothing: antialiased .

ancestral's user avatar

Just adding this answer. "Stroking" the text is not the same as "Outlining".

Outlining looks great. Stroking looks horrid.

The SVG solution listed elsewhere has the same issue. If you want an outline you need to put the text twice. Once stroked and again not stroked.

Stroking IS NOT Outlining

PS: I’d love to know how to make the SVG be the correct size of any arbitrary text. I have a feeling it’s fairly complicated involving generating the SVG, querying it with Javascript to get the extents, then applying the results. If there is an easier non-JS way, I’d love to know.

Update: As @12me21 points out, in SVG you can use paint-order="stroke" to make it stroke before filling and then you don’t have to repeat the text

gman's user avatar

You could try stacking multiple blured shadows until the shadows look like a stroke, like so:

I mention it just in case someone’s interested, although I wouldn’t call it a solution because it fails in various ways:

  • it doesn’t work in old IE
  • it renders quite differently in every browser
  • applying so many shadows is very heavy to process :S

brohr's user avatar

I was looking for a cross-browser text-stroke solution that works when overlaid on background images. think I have a solution for this that doesn’t involve extra mark-up, js and works in IE7-9 (I haven’t tested 6), and doesn’t cause aliasing problems.

This is a combination of using CSS3 text-shadow, which has good support except IE (http://caniuse.com/#search=text-shadow), then using a combination of filters for IE. CSS3 text-stroke support is poor at the moment.

IE Filters

David Hewitt’s answer involved adding dropshadow filters in a combination of directions. ClearType is then removed unfortunately so we end up with badly aliased text.

I then combined some of the elements suggested on useragentman with the dropshadow filters.

Putting it together

This example would be black text with a white stroke. I’m using conditional html classes by the way to target IE (http://paulirish.com/2008/conditional-stylesheets-vs-css-hacks-answer-neither/).

This mixin for SASS will give smooth results, using 8-axis:

I got better results with 6 different shadows:

Aashish Kumar's user avatar

Working with thicker strokes gets a bit messy, if you have the pleasure of sass try this mixin, not perfect and depending on stroke weight it generates a fair amount of css.

We can use text-stroke

Just piece of cake. Try this instead of using text-shadow

I had this issue as well, and the text-shadow wasn’t an option because the corners would look bad (unless I had many many shadows), and I didn’t want any blur, therefore my only other option was to do the following: Have 2 divs, and for the background div, put a -webkit-text-stroke on it, which then allows for as big of an outline as you like.

Using this, I was able to achieve an outline, because the stroke-width method was not an option if you want your text to remain legible with a very large outline (because with stroke-width the outline will start inside the lettering which makes it not legible when the width gets larger than the letters.

Note: the reason I needed such a fat outline was I was emulating the street labels in «google maps» and I wanted a fat white halo around the text. This solution worked perfectly for me.

enter image description here

Jared's user avatar

Text Shadow Generator

There are lots of great answers here. It would appear the text-shadow is probably the most reliable way to do this. I won’t go into detail about how to do this with text-shadow since others have already done that, but the basic idea is that you create multiple text shadows around the text element. The larger the text outline, the more text shadows you need.

All of the answers submitted (as of this posting) provide static solutions for the text-shadow. I have taken a different approach and have written this JSFiddle that accepts outline color, blur, and width values as inputs and generates the appropriate text-shadow property for your element. Just fill in the blanks, check the preview, and click to copy the css and paste it into your stylesheet.

Needless Appendix

Apparently, answers that include a link to a JSFiddle cannot be posted unless they also contain code. You can completely ignore this appendix if you want to. This is the JavaScript from my fiddle that generates the text-shadow property. Please note that you do not need to implement this code in your own works:

Обводка текста CSS: создание эффекта контурного текста

Обводка текста CSS основана на свойстве -webkit-text-stroke , которое принимает в качестве значений ширину и цвет:

Значение width указывает, какой толщины будет контур. Значение color определяет цвет контура. Все довольно просто. Пример применения этого свойства:

Следует отметить, что у свойства text-stroke есть префикс webkit . Это может показаться странным, но это единственная версия, поддерживаемая всеми браузерами. Даже браузеры, не использующие webkit , такие как Firefox и Edge , поддерживают это свойство.

Размещаем все вместе

Мы рассмотрели свойство -webkit-text-stroke и его использование. Теперь проиллюстрируем все это.

Перед тем, как сделать обводку текста CSS , создайте новый документ HTML и добавьте в него следующую разметку:

Сохраните веб-страницу, а затем откройте ее в браузере. Вы должны увидеть примерно следующее:

Размещаем все вместе

Взгляните на разметку, отвечающую за CSS обводку текста белым цветом, который мы видим:

Мы хотим разместить текст внутри элемента span и отобразить его с эффекта контура, о котором говорили ранее. Обводка должна быть шириной 1 пиксель и иметь зеленовато-лимонный цвет. Для этого добавьте следующий код в нижнюю часть блока style ( ниже существующих правил стиля ):

После этого сохраните веб-страницу и откройте ( обновите ) ее в браузере. Вы должны увидеть появившийся контур:

Размещаем все вместе - 2

Если хотите отобразить только контур текста, все, что нужно сделать, это присвоить CSS свойству color значение transparent :

После этого текст « Of course you did! » будет отображен только с помощью контура!

Работа со старыми браузерами

Свойство text-stroke поддерживается браузерами хорошо . Но, возможно, вы захотите отобразить альтернативный вариант для тех пользователей, которые используют старые версии браузеров. В этих случаях нужно « закрасить » текст сплошным цветом. Это можно сделать, комбинируя свойства color и -webkit-fill-color :

В этом случае текст будет отображаться сплошным цветом для старых свойств ( с помощью свойства color ). Если поддерживаются свойства -webkit-text , то webkit-text-fill-color переопределит свойство цвета и отобразит контур с прозрачным цветом заливки.

Заключение

Свойство -webkit-text-stroke упрощает создание обводки текста CSS . Раньше, если бы мы хотели сделать это, пришлось бы полагаться на изображения, хитрости с тенями, использование специального контурного шрифта. Теперь нам не нужно все это делать!

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

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