Css text decoration height

CSS Text Decoration

In this chapter you will learn about the following properties:

  • text-decoration-line
  • text-decoration-color
  • text-decoration-style
  • text-decoration-thickness
  • text-decoration

Add a Decoration Line to Text

The text-decoration-line property is used to add a decoration line to text.

Tip: You can combine more than one value, like overline and underline to display lines both over and under a text.

Example

h1 <
text-decoration-line: overline;
>

h2 text-decoration-line: line-through;
>

h3 text-decoration-line: underline;
>

p text-decoration-line: overline underline;
>

Note: It is not recommended to underline text that is not a link, as this often confuses the reader.

Specify a Color for the Decoration Line

The text-decoration-color property is used to set the color of the decoration line.

Example

h1 <
text-decoration-line: overline;
text-decoration-color: red;
>

h2 text-decoration-line: line-through;
text-decoration-color: blue;
>

h3 text-decoration-line: underline;
text-decoration-color: green;
>

p text-decoration-line: overline underline;
text-decoration-color: purple;
>

Specify a Style for the Decoration Line

The text-decoration-style property is used to set the style of the decoration line.

Example

h1 <
text-decoration-line: underline;
text-decoration-style: solid;
>

h2 text-decoration-line: underline;
text-decoration-style: double;
>

h3 text-decoration-line: underline;
text-decoration-style: dotted;
>

p.ex1 text-decoration-line: underline;
text-decoration-style: dashed;
>

p.ex2 text-decoration-line: underline;
text-decoration-style: wavy;
>

p.ex3 text-decoration-line: underline;
text-decoration-color: red;
text-decoration-style: wavy;
>

Specify the Thickness for the Decoration Line

The text-decoration-thickness property is used to set the thickness of the decoration line.

Example

h1 <
text-decoration-line: underline;
text-decoration-thickness: auto;
>

h2 text-decoration-line: underline;
text-decoration-thickness: 5px;
>

h3 text-decoration-line: underline;
text-decoration-thickness: 25%;
>

p text-decoration-line: underline;
text-decoration-color: red;
text-decoration-style: double;
text-decoration-thickness: 5px;
>

The Shorthand Property

The text-decoration property is a shorthand property for:

  • text-decoration-line (required)
  • text-decoration-color (optional)
  • text-decoration-style (optional)
  • text-decoration-thickness (optional)

Example

h1 <
text-decoration: underline;
>

h2 text-decoration: underline red;
>

h3 text-decoration: underline red double;
>

p text-decoration: underline red double 5px;
>

A Small Tip

All links in HTML are underlined by default. Sometimes you see that links are styled with no underline. The text-decoration: none; is used to remove the underline from links, like this:

Example

All CSS text-decoration Properties

Property Description
text-decoration Sets all the text-decoration properties in one declaration
text-decoration-color Specifies the color of the text-decoration
text-decoration-line Specifies the kind of text decoration to be used (underline, overline, etc.)
text-decoration-style Specifies the style of the text decoration (solid, dotted, etc.)
text-decoration-thickness Specifies the thickness of the text decoration line
Читайте также:  Javascript прокрутить до конца

Источник

text-decoration

The text-decoration shorthand CSS property sets the appearance of decorative lines on text. It is a shorthand for text-decoration-line , text-decoration-color , text-decoration-style , and the newer text-decoration-thickness property.

Try it

Text decorations are drawn across descendant text elements. This means that if an element specifies a text decoration, then a child element can’t remove the decoration. For example, in the markup

This text has some emphasized words in it.

, the style rule p < text-decoration: underline; >would cause the entire paragraph to be underlined. The style rule em < text-decoration: none; >would not cause any change; the entire paragraph would still be underlined. However, the rule em < text-decoration: overline; >would cause a second decoration to appear on «some emphasized words».

Constituent properties

This property is a shorthand for the following CSS properties:

Syntax

text-decoration: underline; text-decoration: overline red; text-decoration: none; /* Global values */ text-decoration: inherit; text-decoration: initial; text-decoration: revert; text-decoration: revert-layer; text-decoration: unset; 

The text-decoration property is specified as one or more space-separated values representing the various longhand text-decoration properties.

Values

Sets the kind of decoration used, such as underline or line-through .

Sets the color of the decoration.

Sets the style of the line used for the decoration, such as solid , wavy , or dashed .

Sets the thickness of the line used for the decoration.

Formal definition

  • text-decoration-color : currentcolor
  • text-decoration-style : solid
  • text-decoration-line : none
  • text-decoration-line : as specified
  • text-decoration-style : as specified
  • text-decoration-color : computed color
  • text-decoration-thickness : as specified
  • text-decoration-color : a color
  • text-decoration-style : discrete
  • text-decoration-line : discrete
  • text-decoration-thickness : by computed value type

Formal syntax

Examples

Demonstration of text-decoration values

.under  text-decoration: underline red; > .over  text-decoration: wavy overline lime; > .line  text-decoration: line-through; > .plain  text-decoration: none; > .underover  text-decoration: dashed underline overline; > .thick  text-decoration: solid underline purple 4px; > .blink  text-decoration: blink; > 
p class="under">This text has a line underneath it.p> p class="over">This text has a line over it.p> p class="line">This text has a line going through it.p> p> This a class="plain" href="#">link will not be underlineda>, as links generally are by default. Be careful when removing the text decoration on anchors since users often depend on the underline to denote hyperlinks. p> p class="underover">This text has lines above em>andem> below it.p> p class="thick"> This text has a really thick purple underline in supporting browsers. p> p class="blink"> This text might blink for you, depending on the browser you use. p> 

Result

Specifications

Browser compatibility

BCD tables only load in the browser

See also

  • The individual text-decoration properties are text-decoration-line , text-decoration-color , text-decoration-style , and text-decoration-thickness .
  • The text-decoration-skip-ink , text-underline-offset , and text-underline-position properties also affect text-decoration, but are not included in the shorthand.
  • The list-style attribute controls the appearance of items in HTML and lists.

Found a content problem with this page?

This page was last modified on Apr 20, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

Нестандартное подчёркивание текста на чистом CSS. Свойство text-decoration

В HTML есть несколько тегов, которые помогают обратить внимание на текст — подчеркнуть, выделить его или акцентировать на чём-то внимание. У таких тегов есть стили по умолчанию, и к некоторым из них мы давно привыкли.

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

Отрывки текста с выделением по умолчанию

Но с помощью text-decoration текст можно даже подчеркнуть сверху (что? да!). Давайте разберёмся, как это сделать.

Свойство text-decoration

  • line-through — зачёркивание посередине текста;
  • overline — надчёркивание, над текстом;
  • underline — подчёркивание, под текстом;
  • none — не используется декор;
  • inherit — наследуется.

Например, свойство для подчёркнутого текста записывается просто как

text-decoration — это сокращённая форма записи для набора CSS-свойств text-decoration-line , text-decoration-color , text-decoration-style и text-decoration-thickness . Перечисленные свойства используются для более тонкой настройки параметров подчёркивания.

text-decoration-line

text-decoration-line — отвечает за тип линии: подчёркнуто, перечёркнуто, без подчёркивания, подчёркивание над текстом, а не под ним.

text-decoration-line: underline; /* обычное подчёркивание */ 
text-decoration-line: line-through; /* текст перечёркнут */ 
text-decoration-line: overline; /* подчёркивание над текстом */ 

text-decoration-line может принимать сразу несколько значений, например, text-decoration-line: underline line-through; . В этом случае у текста будет подчёркивание и зачёркивание.

text-decoration-color

text-decoration-color управляет цветом подчёркивания. По умолчанию он, то есть цвет подчёркивания, совпадает с цветом текста.

 .red-line 

Красная пунктирная линия

text-decoration-style

Стиль линии (сплошная, волнистая, точками, тире и другие) настраивается через CSS-свойство text-decoration-style .

  • solid — обычная сплошная линия;
  • double — двойная линия;
  • dotted — пунктирная линия (пунктир из точек);
  • dashed — тоже пунктирная линия, но пунктир из коротких линий;
  • wavy — волнистая линия.

text-decoration-thickness

text-decoration-thickness задаёт толщину линии.

text-decoration-thickness: 5px; 

5 пикселей — художественная условность :)

text-underline-offset

До недавнего времени внешним видом подчёркивания управляли только эти четыре CSS-свойства ( text-decoration-line , text-decoration-color , text-decoration-style и text-decoration-thickness ). Но были ситуации, когда перечисленных свойств было недостаточно. К примеру, нужно реализовать выделение активного пункта меню на сайте:

Активный пункт меню выделен нестандартным подчёркиванием

Если использовать только text-decoration , нужное подчёркивание не реализовать. Его, конечно, можно добавить за счёт нижней границы, стилизации через псевдоэлементы или другими странными методами.

Но всё упростилось с появлением text-underline-offset . Свойство устанавливает смещение подчёркивания от его исходного положения и используется в связке со свойством text-decoration .

У свойства text-underline-offset хорошая браузерная поддержка, оно работает в большинстве современных браузеров, кроме Firefox под Android.

🔥 Как работать в Фигме Инструкция для начинающих.

Как узнать параметры нестандартного подчёркивания

Все параметры для подчёркивания будем доставать из макета в Figma.

Нам нужны два параметра — расстояние от текста до линии и толщина линии. Цвет подчёркивания обычно совпадает с цветом текста, поэтому специально искать этот параметр обычно не нужно.

Расстояние от текста до линии

Чтобы измерить расстояние между объектами, достаточно выбрать первый объект, нажать Alt/Option и навести на второй. Выделяем текстовый слой и с зажатой клавишей Alt/Option наводим курсор мыши на линию подчёркивания. В тултипе оранжевого цвета выводится количество пикселей между текстом и объектом, на который навели. В нашем случае — это значение 20 .

Запишем это значение в CSS-свойство text-underline-offset :

.active color: #ffffff; text-decoration: underline; /* Смещаем подчёркивание на 20 пикселей вниз */ text-underline-offset: 20px; > 

Толщина линии подчеркивания

Выделим объект с подчёркиванием. После этого на панели справа, на вкладке Inspect найдём свойства объекта. Нас интересует свойство Height (высота).

Свойство отображается и в разделе Properties, и в разделе Code. В примере толщина подчёркивания — 4 пикселя. Напомним, в CSS толщиной подчёркивания управляет свойство text-decoration-thickness . Допишем в правило определение толщины подчёркивания:

А теперь давайте сравним с помощью расширения Perfect Pixel макет и полученную вёрстку.

Расхождением с Perfect Pixel

Это произошло из-за того, что по умолчанию отступ отсчитывается от базовой линии текста, а Фигма показывает расстояние от нижней границы текстового блока.

💡 Базовая линия — эта линия на которой буквы «стоят». Она проходит по самому нижнему краю букв c плоской нижней частью.

Тонкая синяя линия по нижнему краю надписи

Способов решить задачу (имеется в виду попасть в макет) несколько.

  1. Обновить границы слоя, чтобы они соответствовали базовой линии. Этот способ измерения предлагает сама Фигма в документации. В Фигме есть возможность текстовому блоку задать Fixed Size.

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

  1. Использовать новое CSS-свойство text-underline-position со значением under . В этом случае базовая «нулевая» позиция будет установлена не по базовой линии, а по нижней границе блока, и text-underline-offset будет отсчитываться от того же базового положения, что и в редакторе Figma.

На этом всё — пробуйте, экспериментируйте и изучайте вёрстку, а мы вам в этом поможем.

«Доктайп» — журнал о фронтенде. Читайте, слушайте и учитесь с нами.

Источник

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