Css text decoration underline отступ

Control underline position on text-decoration: underline

The example above has an underline by default. is there a way to nudge that underline down by a few pixels so that there is more space between the text and the underline?

9 Answers 9

2020

2012

The only way to do that is to use a border instead of an underline. Underlines are notoriously inflexible.

Here’s a demo. If that’s not enough space, you can easily add more — if it’s too much, that’s a little less convenient.

It’s the easiest solution in most cases, but doesn’t work when you want a big line-height to have a big click target (in a menu for example) but don’t want to push the «underline» (border) as far below. Then, the text-underline-position or :after solutions work best.

@YannDìnendal: I’m not sure how text-underline-position could work at all, given that it’s about which side of the text the underline appears on… but yes, if you have a single line of text you can use ::after . A solution that allows both line breaks and a big click target at the expense of maybe needing more markup is to put the underlined text in a vertically-centred wrapper.

Читайте также:  Сложение двух строк си шарп

You can use pseudo before and after like this. It works well and is completely customizable.

p < line-height: 1.6; >.underline < text-decoration: none; position: relative; >.underline:after < position: absolute; height: 1px; margin: 0 auto; content: ''; left: 0; right: 0; width: 90%; color: #000; background-color: red; left: 0; bottom: -3px; /* adjust this to move up and down. you may have to adjust the line height of the paragraph if you move it down a lot. */ >

This is some example text. From this page, you can read more example text, or you can visit the bookshop to read example text later.

Here’s a more advanced demo with a screenshot attached I made that animates the underline on hovering, changes colors, etc.

underline css

This ain’t work if you need, for example, the whole

element underlined and white-space:wrap enabled

This also won’t work if your anchor link spans more than a single line, even by itself without other content around it. Thanks for the alternative idea though.

I am using this for header underline animation with fewer modifications by using responsive css units.

Also won’t work if your text needs to have a lot of padding and you can’t put additional html element to wrap your text with. Just something to think of.

There is the proposed text-underline-position property in CSS 3, but it seems that it has not been implemented in any browser yet.

So you would need to use the workaround of suppressing the underline and adding a bottom border, as suggested in other answers.

Note the the underline does not add to the total height of an element but bottom border does. In some situations, you might wish to use outline-bottom – which does not add to the total height – instead (though it is not as widely supported as border-bottom ).

Источник

Нестандартное подчёркивание текста на чистом 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.

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

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

Источник

text-underline-offset

The text-underline-offset CSS property sets the offset distance of an underline text decoration line (applied using text-decoration ) from its original position.

Try it

text-underline-offset is not part of the text-decoration shorthand. While an element can have multiple text-decoration lines, text-underline-offset only impacts underlining, and not other possible line decoration options such as overline or line-through .

Syntax

/* Single keyword */ text-underline-offset: auto; /* length */ text-underline-offset: 0.1em; text-underline-offset: 3px; /* percentage */ text-underline-offset: 20%; /* Global values */ text-underline-offset: inherit; text-underline-offset: initial; text-underline-offset: revert; text-underline-offset: revert-layer; text-underline-offset: unset; 

The text-underline-offset property is specified as a single value from the list below.

Values

The browser chooses the appropriate offset for underlines.

Formal definition

Initial value auto
Applies to all elements. It also applies to ::first-letter and ::first-line .
Inherited yes
Percentages refer to the font size of the element itself
Computed value as specified
Animation type by computed value type

Источник

How make text-decoration: underline with 2px padding?

I like an obedient frotend developer must create underline with 2px padding instead of 1px by default. Is exist simple solution for this? PS Yeahh guys, I know about div with black backgrond color and 1px * Npx and position: relative, but It’s so slowly.

CSS3 has a lot of new text-decoration properties these days. Please check out alligator.io/css/text-decoration Example: ´text-decoration-position: under;´ and ´text-decoration-skip: ink;´ Please note that this is probably not backward compatible with older browsers.

11 Answers 11

For cross-browsing it is better to use text-underline-offset over the text-underline-position , because text-underline-position isn’t supported by iOS Safari

You could wrap the text in a span and give it a border-bottom with padding-bottom:2px; .

In CSS exist property, — text-decoration:underline. It’s draw line below text with padding 1px. I need same effect, but with 2px.

My understanding is you can’t change the default on text-decoration . That’s why you need a workaround like what I suggested.

A great way to do this without adding and extra spans and having more control is using the :after selector.

Useful especially for navigation menus:

If you want more or less space between the text and the underline, add a margin-top .

If you want a thicker underline, add more height :

This is great, except I am noticing it ruins the horizontally centered alignment with flexbox because it adds height to the item.

Welcome to Stack Overflow. Code-only answers are discouraged on Stack Overflow because they don’t explain how it solves the problem. Please edit your answer to explain what this code does and how it improves on the many other upvoted answers this question has already, so that it is useful to other users with similar issues.

text-decoration: underline; text-underline-position: under; 

Источник

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