Text Outline

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

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

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

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

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

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

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

     body < background-color: #0F1020; padding: 100px; >#textContainer p  

Did you know that your fingerprint is unique? Of course you did!

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

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

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

 

Did you know that your fingerprint is unique? Of course you did!

Мы хотим разместить текст внутри элемента 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 . Раньше, если бы мы хотели сделать это, пришлось бы полагаться на изображения, хитрости с тенями, использование специального контурного шрифта. Теперь нам не нужно все это делать!

МЛ Мария Логутенко автор-переводчик статьи «

Источник

Adding Outline to Text Using CSS

submit your article

With CSS, you can design your text in many possible ways. You can add different colors, shadows, underlines or style it in a number of ways. In this post, you will be looking at different methods by which outline, or text stroke, can be added to text.

We will be covering two methods by which you can add outlines to your text. There is a third one also, but currently it is not supported by any browser.

Using text-stroke property

The text-stroke property adds stroke to your text. It can be used to change the width and color of the text. This property is only supported by WebKit-based browsers and that too on using the -webkit- prefix.

 id="example1">This text has stroke 
#example1 color: white; font-size: 40px; -webkit-text-stroke-width: 2px; -webkit-text-stroke-color: black; > 

-webkit-text-stroke-width and -webkit-text-stroke-color specifies the width and the color of the stroke respectively. These are the two longhand properties for the shorthand property -webkit-text-stroke which specifies both the stroke color and the width at one go. Thus, the above CSS code is equivalent to the one shown below.

#example2 color: white; font-size: 40px; -webkit-text-stroke: 2px black; > 

You won’t be able to see the above text if your browser does not support the text-stroke property, because it has a white font color. In order to make the text visible in all these browsers, give it any text color other than the background color so that it becomes visible in all the browsers which do not support this property and use the -webkit-text-fill-color property to override the text color in all WebKit-based browsers.

 id="example3">The text stroke will not be visible for some browsers 
#example3 color: black; font-size: 34px; -webkit-text-stroke: 1px black; -webkit-text-fill-color: white; > 

The text stroke will not be visible for some browsers

The above text will appear black in all the browsers which do not support the text-transform property. For browsers which support this property, -webkit-text-fill-color overrode the black text color to make it white.

Now, let’s come to another method which can be used to add oulines to your text.

Using text-shadow property

Since text-stroke doesn’t have much browser support, you can use the text-shadow property which has comparatively large support from browsers.

 id="example4">Stroke using text shadow 
#example4 color: white; font-size: 40px; text-shadow: -1px 1px 0 #000, 1px 1px 0 #000, 1px -1px 0 #000; -1px -1px 0 #000; > 

In the above demo, four text shadows (top-right, bottom-right, bottom-left and top-left) are given setting the blur radius 0. This effect is similar to that generated by the first method.

This method has an added advantage. We can adjust the horizontal and vertical shadows according to what suits the text. Adding a little blur radius will also give it a better look as in the following demo.

 id="example5">Stroke with blur radius 
#example5 color: white; font-size: 40px; text-shadow: -1px 1px 2px #000, 1px 1px 2px #000, 1px -1px 0 #000, -1px -1px 0 #000; > 

A drawback of using text shadows is that if you give the shadow length greater than 1px, then you may see discontinuous stroke.

More with text stroke

You can combine the text-stroke and the text-shadow properties to give another great effect.

#example6 color: white; font-size: 40px; -webkit-text-stroke: 1px #23430C; text-shadow: -1px 1px 2px #23430C, 1px 1px 2px #23430C, 1px -1px 0 #23430C, -1px -1px 0 #23430C; > 
 id="example7">Text Stroke  id="example8">Text Stroke 
#example7 color: white; font-size: 47px; -webkit-text-stroke: 3px #E21F03; > #example8 color: white; font-size: 47px; -webkit-text-stroke: 5px #E21F03; > 

The above demo gives the effect of a thin white colored line following the path of the text for the first text and a curvy bold look for the second text. This can be achieved by just increasing the stroke width.

Have a look at some more text stroke effects

 id="example9">Text Stroke  id="example10">Text Stroke  id="example11">Text Stroke 
#example9 color: white; font-size: 47px; -webkit-text-stroke: 1px #F8F8F8; text-shadow: 0px 1px 4px #23430C; > #example10 color: white; font-size: 47px; -webkit-text-stroke: 1px #F8F8F8; text-shadow: 0px 2px 4px blue; > #example11 color: #333; background-color: black; font-size: 56px; -webkit-text-stroke: 1px #282828; text-shadow: 0px 4px 4px #282828; > 

These were some cool effects which you can add to your text using the above properties. You can come up with more beautiful text stroke effects by combining and altering the values of different properties like color, blur radius, stroke width and so on.

Browser Support

As discussed earlier, the text-stroke property is supported with the -webkit- prefix by the WebKit-based browsers. This is supported by Chrome, Safari, Opera and Android. On the other hand, text-shadow is supported by almost all the browsers.

There is also a third property text-outline for adding outline to text, but currently it is not supported by any browser.

Conclusion

A slight touch of stroke can give a vibrant look to your text. Although text-stroke serves the purpose by uniformly adding a smooth outline, I prefer using text-shadow due to its good browser support. The latter is not intended for adding outlines, but is a very good CSS hack that gives you the effect you are looking for. Moreover, you can give blur effect with shadows which can add depth to your layout. Although text-shadow does not give good results if the shadow length is greater than 1px, you can always use a combination of text-shadow and text-stroke .

Источник

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: Another possibility is only applying when supported:

@supports (-webkit-text-stroke: 1px black) < h1 < -webkit-text-stroke: 1px black; -webkit-text-fill-color: white; >>

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

Mobile / Tablet

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.

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.

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: 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). 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).

/* Only the color will change, not the width */ @keyframes colorchange < 0% < -webkit-text-stroke: 10px red; >100% < -webkit-text-stroke: 20px green; >>
  • text-stroke (CSS-Tricks Almanac)
  • Text Stroke: Stuck in the Middle With You (Chris Coyier)
  • CSS Text Shadow (Chris Coyier)
  • Classy Text Shadows (Chris Coyier)
  • Cool Hover Effects That Use CSS Text Shadow (Temani Afif)
  • How to Create Neon Text With CSS (Silvia O’Dwyer)
  • The CSS text-shadow property (Alligator.io)

Источник

Читайте также:  Стили вопрос ответ css
Оцените статью