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!

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

Читайте также:  Java импорт своих классов

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

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

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

Источник

Как добавить вокруг текста рамку определенного цвета?

Для создания рамки вокруг текста используйте стилевое свойство border , добавляя его к соответствующему селектору. Например, если для текста применяется тег

, то для него надо установить следующий стиль.

Применение свойства border к текстовому абзацу продемонстрировано в примере 1.

Пример 1. Рамка вокруг абзаца

HTML5 CSS 2.1 IE Cr Op Sa Fx

     p 

Нет страшнее зверя в сибирских лесах, чем разъяренный заяц-мутант. Вы видели, какие у него зубы? О, даже медведь боится этих зубов! А, как известно, медведи больше ничего не боятся.

Результат данного примера показан на рис. 1.

Вид рамки вокруг абзаца

Рис. 1. Вид рамки вокруг абзаца

Следует учитывать, что в тексте может быть несколько абзацев и вокруг каждого тогда возникнет рамка. В подобных случаях лучше воспользоваться тегом , для которого и требуется установить стиль. А текст добавить уже внутрь этого контейнера (пример 2).

Пример 2. Рамка вокруг слоя

HTML5 CSS 2.1 IE Cr Op Sa Fx

     .outline 
Перед тем как убить героя, антагонист обязательно рассказывает ему про все свои злодеяния, чтобы создать необходимую паузу. Разумеется, любой протагонист весьма умело использует данное время против самого злодея.

Из этого правила есть только одно исключение. Герой может не суетиться, тянуть время, и вообще ничего не делать, потому что на помощь придут его друзья.

Источник

How To Add HTML Border Around Text

How To Add HTML Border Around Text

In HTML, you can add a box around text, or a border around text and change it to any color or thickness.

This can be achieved using some CSS.

CSS is applied to HTML elements to alter the look of the elements.

In the below examples, we will see two ways we can add HTML border around text and can colorize it.

Add HTML Border Around Text Using Inline CSS

You can add inline css to your HTML elements and add a border around your text elements.

Using the style attribute on HTML elements, you can give the border property and add a border.

This is an example of a HTML border around some text.

Let’s look at some HTML code

This is an example of a HTML border around some text.

In the above example, we can see that we used the style attribte and used the border styles to add a border around the text.

Add HTML Border Around Text Using External CSS

The concept remains the same weather you are applying inline CSS or external CSS.

We make use of the CSS border property to assign a border to any element.

This is an example of a HTML border around some text using external css.

Let’s look at some the HTML code for the above

This is an example of a HTML border around some text using external css.

Recent Posts

HTML Option Selected Attribute

HTML Option Selected Attribute

In this blog post, we will learn about the Selected attribute in HTML Option element. A dropdown list is created using the Select tag in HTML.

Create A REST Web API In ASP.NET Core 3.1 - ASP.NET Core CRUD Web API

Create A REST Web API In ASP.NET Core 3.1 — ASP.NET Core CRUD Web API

In this blog post, we will create an ASP.NET Core Web API from scratch step by step. We will follow RESTful principles and create CRUD operations and create an ASP.NET Core Web API in .NET Core version 3.1.

During the implementation, we install and use Entity Framework Core to connect to our SQL Server database and perform CRUD operations.

Char Array To String In C#

Char Array To String In C#

In this blog post, we will learn how to convert a Char Array To String in C#. A char array is an array of character types. That means they hold a single character value in each of its elements.

C# Dictionary Foreach - Iterate Over Dictionary C#

C# Dictionary Foreach — Iterate Over Dictionary C#

In this blog post, we will learn how to iterate over a dictionary in C#. We will use a few different ways to iterate over the dictionary.

Convert List To IEnumerable In C# - AsEnumerable Method In C#

Convert List To IEnumerable In C# — AsEnumerable Method In C#

In this blog post, we will see how we can convert a List to IEnumerable in C#. A List in C# already implements an IEnumerable but you may still feel the need to convert a List to IEnumerable in C#.

Источник

How to create a colored border around text with HTML and CSS

Blue colored border around the word Border

Computer Hope

Using borders, you can add a box around text, and set or change the border to nearly any color. A border in your HTML (hypertext markup language) page helps bring attention to a section of text or surround any other HTML elements. Borders are added to HTML using CSS (cascading style sheets).

Border CSS

Border CSS has properties for line type (solid, dotted, etc.), line width, and line color. The following table elaborates on the details of each and which values are acceptable to make them work properly.

CSS Border Property Valid Values Example
border (all sides)
border-top (top line only)
border-right (right line only)
border-bottom (bottom line only)
border-left (left line only)
Any valid combination of the properties below. dotted thin black
border-style (all sides) solid
dotted
dashed
double
groove
ridge
inset
outset
none
hidden
solid
border-width (all sides) width, specified in px, pt, cm, em
width, specified as thin, medium, or thick
3 px
border-color (all sides) color, specified as color code
color, specified as named color
#FF00FF

Add a border using the style attribute

HTML tags can be formatted using a style attribute. To add a border using the style attribute, add the border CSS inside the quotes after style=.

In the example below, we surrounded a paragraph ( ) with a solid red border that is 3 pixels wide.

First example with text surrounded by a red border.
This example also has multiple lines.

To create the example above, the code below is used.

<p style="border-width:3px; border-style:solid; border-color:#FF0000; padding: 1em;">First example with text surrounded by a red border.
This example also has multiple lines.p>

In the code above, the CSS is defining the border size («px» short for pixel), style type, and border color. The style of the border is how the border appears on the screen. In our example, we used the «solid» border style. The border color defines the color you want to use for the border. In the example above, the color code #FF0000 is used, which is the color code for red.

A border can also be applied to only one side. For example, with the heading of this page, we have a grey underline. This line is actually a border, achieved with the CSS code border-bottom: 1px solid #93B0D2;.

Placing the CSS formatting inside the style attribute can be applied to other HTML tags, such as the div tag or span tag. In the example below, a border is added to a single word using the span tag.

Here is a second example with a bordered word , with different styles applied to the top, bottom, left, and right.

To create the example above, the following code is used.

<span style="border-top:thick green solid;border-bottom:thick green double;border-left:4px #2330C4 dotted; border-right:thin #2330C4 dotted;padding-left:2px;padding-right:2px;">wordspan>

Add a border using a CSS class

The appearance of elements on a web page may also be defined with inline CSS. Inline CSS is defined in your HTML document, in the element. Or, you can define the CSS in an external file with the .css extension. Then, you can link to this file from any HTML page, and elements in that document can use the CSS styles. For example, with the CSS code below, a new class named «borderexample» is created that can be applied to any HTML tag.

Using the code above, if you want to apply this border style to an HTML paragraph or word, you can type something similar to the example below.

<p class="borderexample">Here is an example of a border created using CSS.p> <p>The class can also be <span class="borderexample">usedspan> on the span tag.p>

On your web page, the code above would look like the example below.

Here is an example of a border created using CSS.

The class can also be used on the span tag.

Источник

Оцените статью