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

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

  • автор:

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

Sometimes we need to create text and adding the outline to the text. There are mainly two methods to create a border to the fonts which are listed below:

  • Using text-shadow property
  • Using text-stroke property

Method 1: Using text-shadow property: The text-shadow property is used to add font border or shadow to the text.
Syntax:

Property Values:

  • h-shadow: It sets horizontal shadow around the font.
  • v-shadow: It sets the vertical shadow around the font.
  • blur-radius: It sets the blur radius around the font.
  • color: It sets color around the font.
  • none: It does not set anything around the font.
  • initial: It sets the font border to its default value.
  • inherit: It inherits the property values from its parent values.

Return Value: It returns a font border/shadow around the text.
Example 1: This example uses text-shadow property to create shadow to the text.

Adding Stroke to Web Text

Fonts on the web are essentially vector-based graphics. That’s why you can display them at 12px or 120px and they remain crisp and relatively sharp-edged. Vector means that their shape is determined by points and mathematics to describe the shape, rather than actual pixel data. Because they are vector, it would make sense if we could do things that other vector programs (e.g. Adobe Illustrator) can do with vector text, like draw a stroke around the individual characters. Well, we can! Example:

You might be thinking “Cool, but if only some browsers support this, if I set my text color to white and my background is white , the stroke makes it look cool in supporting browsers but entirely disappears in non-supporting browsers!”

One possibility is this:

Shown here with @font-face font Anime Ace 2 by Nate Piekos:

Properly stroked! Fallback to solid color. Shown here in Firefox

Another possibility is only applying when supported:

This browser support data is from Caniuse, which has more detail. A number indicates that browser supports the feature at that version and up.

Desktop
Chrome Firefox IE Edge Safari
4* 49* No 15* 3.1*
Mobile / Tablet
Android Chrome Android Firefox Android iOS Safari
110* 110* 2.1* 4.0-4.1*

We can take this a bit further by not relying on the WebKit proprietary entirely. We can use the text-shadow property (supported in Firefox, Opera, and IE 10 as well) and simulate a stroke. We’ll use four shadows, each 1px offset of black with no spread, one each to the top right, top left, bottom left, and bottom right. We’ll remove the WebKit proprietary -webkit-text-fill-color in favor of color since we’re cross-browser compatible now. The only holdout would be IE9 and down, which of course you can use IE-specific stylesheets to account for.

This is a stroke using all text-shadow. Pretty close to just as good as a real stroke. The primary issue is that you can only get 1px of stroke this way. Any more, and you see gaps. Any more with WebKit text stroke and there is issues too though, so it’s kind of a horse apiece.

Using both a stroke and a shadow can be a great effect. Let’s toss on a WebKit stroke, the all-around text-shadow stroke, as well as a deeper text-shadow stroke.

Lookin’ good

If you are familiar with Adobe Illustrator, you may know that you can align a stroke on the inside of a shape, outside, or centered. That option looks like this in the palette:

From left to right: center, inside, outside

For reasons unbeknownst to me, text in Illustrator can only be set to center stroke alignment as well. Once you expand the text into regular vector paths though, all three options become available. Reminder from Sam Frysteen: add a new stroke in the Appearance panel and move it below your text (basically mimics outside stroke alignment).

From top to bottom: inside, centered, outside.

Only outside text stroke alignment looks any good at all to me. It’s unfortunate, both for CSS and for Illustrator, that the unchangeable default is centered. The solution is just not to go too crazy with the thickness of your stroke border and things should be OK. Note: the text-shadow-only solution doesn’t have this problem, but also is unable to stroke any more than 1px.

If you use a pseudo element, you can stroke the same text behind the original text and kinda fake outside stroke.

We have a whole article on this alignment issue: Text Stroke: Stuck In The Middle With You. A minor bit of good news, the paint-order property allows you to esssentially have outside set strokes, once more browsers support it.

There are other things that vector-based graphics programs can do with text. You can squish the letter horizontally / stretch them vertically. This type of text treatment is almost universally frowned upon, so no big loss that we can’t do that. You can also set type on an irregular line (like around a circle). It certainly would be cool to do this with web text. Perhaps we could set text to follow the border path of its parent element.

In Illustrator, we can also tell a stroke how to handle sharp corners: rounded, beveled, or mitered. These can have nice effects, are not possible on the web. However, the WebKit handling of corners is pretty nice at its default (whatever it is), and arguably nicer than any of the options in Illustrator.

For the record, you can use any type of color value for the color of stroke (hex, rgba, hsla, keyword). That means transparent strokes if you want them, which indeed “stack” in that if strokes overlap each other (common) they will be darker.

As far as the keyframe animation, the stroke color will animate but the stroke width will not (weird).

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

Тень текста CSS

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Обводка текста при помощи HTML и CSS

Stroke in HTML
Привет всем хабражителям. Начал я как-то теплым летним вечером рисовать дизайн сайта, попробовал применить однопиксельную обводку текста, смотрелось довольно миленько, решил оставить, наивно думая что большинство последних версий браузеров будут иметь какое-то черновое CSS3 свойство.

Когда дошло дело до верстки того самого элемента, текст в котором нужно было обвести, выяснилось, что text-stroke доступен только в webkit’ах, а это всего-лишь 20-30% браузеров.
Решение проблемы было придуманно довольно быстро: использовать множественную тень.

Если вам стало интересно то добро пожаловать под кат.

Для множественной тени (так-же применимо в современных браузерах и к background) следует описать все тени (я их использовал 4) через запятую, следующим образом:
body <
text-shadow: #000 1px 0 0px, #000 0 1px 0px, #000 -1px 0 0px, #000 0 -1px 0px;
>
в результате получаем правую, нижнюю, левую и верхнюю тени
text-shadow имеет следующий синтакс: #цвет сдвиг_по_х сдвиг_по_у размер_размытости; являеться CSS2.1 свойством.

Для большей наглядности используем сдвиг по больше и раскрасим тень в разные цвета:
body <
color: #000;
text-shadow: text-shadow: #f00 40px 0px 0px, #0f0 0px 20px 0px, #00f 0px -20px 0px, #f0f -40px 0px 0px;
>
Получим следующий результат:
4 shadows

Также можно поиграться с размером шрифта, сдвигом, размытием для получения желаемого результата. К примеру для получения изображения в начале поста использовался следующий вариант:
body <
font: 40px Tahoma;
color: #e7e7e7;
text-shadow: #000 2px 0px 2px, #000 0px 2px 2px, #000 0px -2px 2px, #000 -2px 0px 2px;>

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

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