Способы подчеркивания в css

Рамка вокруг ссылки

При использовании рамок со ссылками возможны два варианта. Первый — рамка вокруг ссылок устанавливается заранее и при наведении на неё курсора меняет свой цвет. И второй — рамка отображается, только когда на ссылку наводится курсор.

В примере 6 показано, как изменять цвет рамки, используя свойство border. Подчёркивание текста через text-decoration можно убрать или оставить без изменения.

Пример 6. Изменение цвета рамки у ссылок

<!DOCTYPE html>
<html>
<head>
<meta charset=»utf-8″>
<title>Ссылки</title>
<style>
a {
border: 1px solid blue; /* Синяя рамка вокруг ссылок */
padding: 2px; /* Поля вокруг текста */
text-decoration: none; /* Скрываем подчёркивание */
}
a:hover {
border: 1px solid red; /* Красная рамка при наведении курсора на ссылку */
}
</style>
</head>
<body>
<p><a href=»link.html»>Ссылка без подчёркивания</a>
</body>
</html>

Чтобы рамка не «прилипала» к тексту, в примере вокруг него установлены поля с помощью padding. Можно также вместе с применением рамки добавить и фон, воспользовавшись свойством background.

Если требуется добавить рамку к ссылкам при наведении на них курсора, то следует позаботиться о том, чтобы текст в этом случае не сдвигался. Достичь этого проще всего добавлением невидимой рамки вокруг ссылки и последующего изменения цвета рамки с помощью псевдокласса :hover. Прозрачный цвет указывается с помощью ключевого слова transparent, в остальном стиль не поменяется.

CSS Reference

CSS ReferenceCSS Browser SupportCSS SelectorsCSS FunctionsCSS Reference AuralCSS Web Safe FontsCSS Font FallbacksCSS AnimatableCSS UnitsCSS PX-EM ConverterCSS ColorsCSS Color ValuesCSS Default ValuesCSS Entities

CSS Properties

align-content
align-items
align-self
all
animation
animation-delay
animation-direction
animation-duration
animation-fill-mode
animation-iteration-count
animation-name
animation-play-state
animation-timing-function

backface-visibility
background
background-attachment
background-blend-mode
background-clip
background-color
background-image
background-origin
background-position
background-repeat
background-size
border
border-bottom
border-bottom-color
border-bottom-left-radius
border-bottom-right-radius
border-bottom-style
border-bottom-width
border-collapse
border-color
border-image
border-image-outset
border-image-repeat
border-image-slice
border-image-source
border-image-width
border-left
border-left-color
border-left-style
border-left-width
border-radius
border-right
border-right-color
border-right-style
border-right-width
border-spacing
border-style
border-top
border-top-color
border-top-left-radius
border-top-right-radius
border-top-style
border-top-width
border-width
bottom
box-decoration-break
box-shadow
box-sizing
break-after
break-before
break-inside

caption-side
caret-color
@charset
clear
clip
clip-path
color
column-count
column-fill
column-gap
column-rule
column-rule-color
column-rule-style
column-rule-width
column-span
column-width
columns
content
counter-increment
counter-reset
cursor

direction
display
empty-cells
filter
flex
flex-basis
flex-direction
flex-flow
flex-grow
flex-shrink
flex-wrap
float
font
@font-face
font-family
font-feature-settings
font-kerning
font-size
font-size-adjust
font-stretch
font-style
font-variant
font-variant-caps
font-weight

gap
grid
grid-area
grid-auto-columns
grid-auto-flow
grid-auto-rows
grid-column
grid-column-end
grid-column-gap
grid-column-start
grid-gap
grid-row
grid-row-end
grid-row-gap
grid-row-start
grid-template
grid-template-areas
grid-template-columns
grid-template-rows

hanging-punctuation
height
hyphens
@import
isolation
justify-content
@keyframes
left
letter-spacing

line-height
list-style
list-style-image
list-style-position
list-style-type

margin
margin-bottom
margin-left
margin-right
margin-top
max-height
max-width
@media
min-height
min-width
mix-blend-mode

object-fit
object-position
opacity
order
outline
outline-color
outline-offset
outline-style
outline-width
overflow
overflow-x
overflow-y

padding
padding-bottom
padding-left
padding-right
padding-top
page-break-after
page-break-before
page-break-inside
perspective
perspective-origin
pointer-events
position
quotes

resize
right
row-gap

scroll-behavior

tab-size
table-layout
text-align
text-align-last
text-decoration
text-decoration-color
text-decoration-line
text-decoration-style
text-indent
text-justify
text-overflow
text-shadow
text-transform
top

transform
transform-origin
transform-style
transition
transition-delay
transition-duration
transition-property
transition-timing-function

unicode-bidi
user-select

vertical-align
visibility

white-space
width
word-break
word-spacing
word-wrap
writing-mode

z-index

Compatibilidade com navegadores

Estamos convertendo nossos dados de compatibilidade para o formato JSON.
Esta tabela de compatibilidade ainda usa o formato antigo,
pois ainda não convertemos os dados que ela contém.
Descubra como você pode ajudar! (en-US)

Feature Firefox (Gecko) Chrome Internet Explorer Opera Safari
Suporte básico 1.0 (1.7 or earlier) 1.0 3.0 3.5 1.0
Valor blink 1.0 (1.7 or earlier)23.0 (23.0) (Yes) (Yes) 4.0
15.0
(Yes)
Propriedade reduzida 6.0 (6.0)36.0 (36.0) Não suportado Não suportado Não suportado 7.1
Feature Firefox Mobile (Gecko) Android IE Phone Opera Mobile Safari Mobile
Suporte básico 1.0 (1.0) (Yes) (Yes) (Yes) (Yes)
Valor blink 1.0 (1.7 or earlier)23.0 (23.0) (Yes) (Yes) 4.0 (Yes)
Propriedade reduzida 6.0 (6.0)
36.0 (36.0)
? ? ? 8

O valor não tem nenhum efeito.

Safari não suporta .

Essa versão do Gecko tem implementação parcial.

CSS Reference

CSS ReferenceCSS Browser SupportCSS SelectorsCSS FunctionsCSS Reference AuralCSS Web Safe FontsCSS Font FallbacksCSS AnimatableCSS UnitsCSS PX-EM ConverterCSS ColorsCSS Color ValuesCSS Default ValuesCSS Entities

CSS Properties

align-content
align-items
align-self
all
animation
animation-delay
animation-direction
animation-duration
animation-fill-mode
animation-iteration-count
animation-name
animation-play-state
animation-timing-function

backface-visibility
background
background-attachment
background-blend-mode
background-clip
background-color
background-image
background-origin
background-position
background-repeat
background-size
border
border-bottom
border-bottom-color
border-bottom-left-radius
border-bottom-right-radius
border-bottom-style
border-bottom-width
border-collapse
border-color
border-image
border-image-outset
border-image-repeat
border-image-slice
border-image-source
border-image-width
border-left
border-left-color
border-left-style
border-left-width
border-radius
border-right
border-right-color
border-right-style
border-right-width
border-spacing
border-style
border-top
border-top-color
border-top-left-radius
border-top-right-radius
border-top-style
border-top-width
border-width
bottom
box-decoration-break
box-shadow
box-sizing
break-after
break-before
break-inside

caption-side
caret-color
@charset
clear
clip
clip-path
color
column-count
column-fill
column-gap
column-rule
column-rule-color
column-rule-style
column-rule-width
column-span
column-width
columns
content
counter-increment
counter-reset
cursor

direction
display
empty-cells
filter
flex
flex-basis
flex-direction
flex-flow
flex-grow
flex-shrink
flex-wrap
float
font
@font-face
font-family
font-feature-settings
font-kerning
font-size
font-size-adjust
font-stretch
font-style
font-variant
font-variant-caps
font-weight

gap
grid
grid-area
grid-auto-columns
grid-auto-flow
grid-auto-rows
grid-column
grid-column-end
grid-column-gap
grid-column-start
grid-gap
grid-row
grid-row-end
grid-row-gap
grid-row-start
grid-template
grid-template-areas
grid-template-columns
grid-template-rows

hanging-punctuation
height
hyphens
@import
isolation
justify-content
@keyframes
left
letter-spacing

line-height
list-style
list-style-image
list-style-position
list-style-type

margin
margin-bottom
margin-left
margin-right
margin-top
max-height
max-width
@media
min-height
min-width
mix-blend-mode

object-fit
object-position
opacity
order
outline
outline-color
outline-offset
outline-style
outline-width
overflow
overflow-x
overflow-y

padding
padding-bottom
padding-left
padding-right
padding-top
page-break-after
page-break-before
page-break-inside
perspective
perspective-origin
pointer-events
position
quotes

resize
right
row-gap

scroll-behavior

tab-size
table-layout
text-align
text-align-last
text-decoration
text-decoration-color
text-decoration-line
text-decoration-style
text-indent
text-justify
text-overflow
text-shadow
text-transform
top

transform
transform-origin
transform-style
transition
transition-delay
transition-duration
transition-property
transition-timing-function

unicode-bidi
user-select

vertical-align
visibility

white-space
width
word-break
word-spacing
word-wrap
writing-mode

z-index

Example Code

Basic CSS

Here’s an example of a basic declaration. A declaration consists of the property and its values for the various longhand properties.

text-decoration: orange dotted underline;

Any omitted values are set to their initial value. So the following is also valid.

text-decoration: underline;

In fact, this is the only syntax recognized by CSS1 and CSS2 (as they don’t support the longhand properties).

So, you could use the following code to provide CSS3 features, while still providing backwards compatibility for CSS1 and CSS2 browsers:

:link {
color: orange;
text-decoration: underline; /* Used by CSS1 and CSS2 browsers */
text-decoration: green dotted underline; /* Used by CSS3 browsers */
}

In CSS1 and CSS2 browsers, both the link text and its underline will be orange. Its underline will be solid (this is the only option prior to CSS3).

In CSS3 browsers, the link text will be orange and its underline will be green. Its underline will also be dotted.

Working Example within an HTML Document

<!DOCTYPE html>
<title>Example</title>
<style>
h1 {
font: 100 3em sans-serif;
color: gold;
text-decoration: overline wavy yellowgreen;
}
</style>

<h1>Overline Example</h1>

Переход для background-size

Обратили внимание, чем отличаются параметры background-position, хотя визуально разницы нет? Один параметр привязан к левой стороне, второй — к правой. Теперь я сделаю переход между одним фоном, который обычно заполняет всю ширину элемента анкора, и отступает при наведении курсора — и между вторым, который повторяет эту же операцию в зеркальном отражении

При этом привязка фонов будет влиять на то, в какую сторону они смещаются:

Теперь я сделаю переход между одним фоном, который обычно заполняет всю ширину элемента анкора, и отступает при наведении курсора — и между вторым, который повторяет эту же операцию в зеркальном отражении. При этом привязка фонов будет влиять на то, в какую сторону они смещаются:

a {
  color: #dfe5f3;
  text-decoration: none;
  background-image: linear-gradient(rgb(176, 251, 188), rgb(176, 251, 188)),
    linear-gradient(#feb2b2, #feb2b2);
  background-size: 100% 2px, 0 2px;
  background-position: 100% 100%, 0 100%;
  background-repeat: no-repeat;
  transition: background-size 2s linear;
}

a:hover {
  background-size: 0 2px, 100% 2px;
}

JavaScript

JS Array
concat()
constructor
copyWithin()
entries()
every()
fill()
filter()
find()
findIndex()
forEach()
from()
includes()
indexOf()
isArray()
join()
keys()
length
lastIndexOf()
map()
pop()
prototype
push()
reduce()
reduceRight()
reverse()
shift()
slice()
some()
sort()
splice()
toString()
unshift()
valueOf()

JS Boolean
constructor
prototype
toString()
valueOf()

JS Classes
constructor()
extends
static
super

JS Date
constructor
getDate()
getDay()
getFullYear()
getHours()
getMilliseconds()
getMinutes()
getMonth()
getSeconds()
getTime()
getTimezoneOffset()
getUTCDate()
getUTCDay()
getUTCFullYear()
getUTCHours()
getUTCMilliseconds()
getUTCMinutes()
getUTCMonth()
getUTCSeconds()
now()
parse()
prototype
setDate()
setFullYear()
setHours()
setMilliseconds()
setMinutes()
setMonth()
setSeconds()
setTime()
setUTCDate()
setUTCFullYear()
setUTCHours()
setUTCMilliseconds()
setUTCMinutes()
setUTCMonth()
setUTCSeconds()
toDateString()
toISOString()
toJSON()
toLocaleDateString()
toLocaleTimeString()
toLocaleString()
toString()
toTimeString()
toUTCString()
UTC()
valueOf()

JS Error
name
message

JS Global
decodeURI()
decodeURIComponent()
encodeURI()
encodeURIComponent()
escape()
eval()
Infinity
isFinite()
isNaN()
NaN
Number()
parseFloat()
parseInt()
String()
undefined
unescape()

JS JSON
parse()
stringify()

JS Math
abs()
acos()
acosh()
asin()
asinh()
atan()
atan2()
atanh()
cbrt()
ceil()
clz32()
cos()
cosh()
E
exp()
expm1()
floor()
fround()
LN2
LN10
log()
log10()
log1p()
log2()
LOG2E
LOG10E
max()
min()
PI
pow()
random()
round()
sign()
sin()
sqrt()
SQRT1_2
SQRT2
tan()
tanh()
trunc()

JS Number
constructor
isFinite()
isInteger()
isNaN()
isSafeInteger()
MAX_VALUE
MIN_VALUE
NEGATIVE_INFINITY
NaN
POSITIVE_INFINITY
prototype
toExponential()
toFixed()
toLocaleString()
toPrecision()
toString()
valueOf()

JS OperatorsJS RegExp
constructor
compile()
exec()
g
global
i
ignoreCase
lastIndex
m
multiline
n+
n*
n?
n{X}
n{X,Y}
n{X,}
n$
^n
?=n
?!n
source
test()
toString()

(x|y)
.
\w
\W
\d
\D
\s
\S
\b
\B
\0
\n
\f
\r
\t
\v
\xxx
\xdd
\uxxxx

JS Statements
break
class
continue
debugger
do…while
for
for…in
for…of
function
if…else
return
switch
throw
try…catch
var
while

JS String
charAt()
charCodeAt()
concat()
constructor
endsWith()
fromCharCode()
includes()
indexOf()
lastIndexOf()
length
localeCompare()
match()
prototype
repeat()
replace()
search()
slice()
split()
startsWith()
substr()
substring()
toLocaleLowerCase()
toLocaleUpperCase()
toLowerCase()
toString()
toUpperCase()
trim()
valueOf()

CSS Свойства

align-contentalign-itemsalign-selfallanimationanimation-delayanimation-directionanimation-durationanimation-fill-modeanimation-iteration-countanimation-nameanimation-play-stateanimation-timing-functionbackface-visibilitybackgroundbackground-attachmentbackground-blend-modebackground-clipbackground-colorbackground-imagebackground-originbackground-positionbackground-repeatbackground-sizeborderborder-bottomborder-bottom-colorborder-bottom-left-radiusborder-bottom-right-radiusborder-bottom-styleborder-bottom-widthborder-collapseborder-colorborder-imageborder-image-outsetborder-image-repeatborder-image-sliceborder-image-sourceborder-image-widthborder-leftborder-left-colorborder-left-styleborder-left-widthborder-radiusborder-rightborder-right-colorborder-right-styleborder-right-widthborder-spacingborder-styleborder-topborder-top-colorborder-top-left-radiusborder-top-right-radiusborder-top-styleborder-top-widthborder-widthbottombox-decoration-breakbox-shadowbox-sizingcaption-sidecaret-color@charsetclearclipcolorcolumn-countcolumn-fillcolumn-gapcolumn-rulecolumn-rule-colorcolumn-rule-stylecolumn-rule-widthcolumn-spancolumn-widthcolumnscontentcounter-incrementcounter-resetcursordirectiondisplayempty-cellsfilterflexflex-basisflex-directionflex-flowflex-growflex-shrinkflex-wrapfloatfont@font-facefont-familyfont-kerningfont-sizefont-size-adjustfont-stretchfont-stylefont-variantfont-weightgridgrid-areagrid-auto-columnsgrid-auto-flowgrid-auto-rowsgrid-columngrid-column-endgrid-column-gapgrid-column-startgrid-gapgrid-rowgrid-row-endgrid-row-gapgrid-row-startgrid-templategrid-template-areasgrid-template-columnsgrid-template-rowshanging-punctuationheighthyphens@importisolationjustify-content@keyframesleftletter-spacingline-heightlist-stylelist-style-imagelist-style-positionlist-style-typemarginmargin-bottommargin-leftmargin-rightmargin-topmax-heightmax-width@mediamin-heightmin-widthmix-blend-modeobject-fitobject-positionopacityorderoutlineoutline-coloroutline-offsetoutline-styleoutline-widthoverflowoverflow-xoverflow-ypaddingpadding-bottompadding-leftpadding-rightpadding-toppage-break-afterpage-break-beforepage-break-insideperspectiveperspective-originpointer-eventspositionquotesresizerighttab-sizetable-layouttext-aligntext-align-lasttext-decorationtext-decoration-colortext-decoration-linetext-decoration-styletext-indenttext-justifytext-overflowtext-shadowtext-transformtoptransformtransform-origintransform-styletransitiontransition-delaytransition-durationtransition-propertytransition-timing-functionunicode-bidiuser-selectvertical-alignvisibilitywhite-spacewidthword-breakword-spacingword-wrapwriting-modez-index

Новые свойства text-decoration

Вы помните, что я обещал подробнее поговорить о text-decoration . Время пришло.

Само по себе это свойство отлично работает, но вы можете добавить несколько экспериментальных свойств для настройки внешнего вида подчеркивания.

  • text-decoration-color
  • text-decoration-skip
  • text-decoration-style

Но слишком сильно не радуйтесь… Поддержка в браузерах — как всегда. Такие дела.

text-decoration-color

Свойство text-decoration-color позволяет вам изменять цвет подчеркивания отдельно от цвета текста. Поддержка этого свойства лучше, чем можно было ожидать — оно работает в Firefox и с префиксом в Safari. Вот в чем загвоздка: если у вас есть выносные элементы, Safari поместит подчеркивание поверх текста.

text-decoration-skip

Свойство text-decoration-skip включает пропуск выносных элементов в подчеркиваемом тексте.

Это свойство нестандартное и работает сейчас только в Safari, с префиксом -webkit- . Safari по умолчанию активирует это свойство, поэтому выносные элементы всегда не перечеркиваются.

Если вы используете Normalize, то учтите, что последние версии отключают это свойство ради последовательного поведения браузеров. И если вы хотите, чтобы подчеркивание не затрагивало выносные элементы, вам надо вручную активировать его.

text-decoration-style

Свойство text-decoration-style предлагает такие же возможности оформления, что и у свойства border-style , добавляя кроме этого стиль wavy .

Вот список доступных значений:

  • dashed
  • dotted
  • double
  • solid

Сейчас свойство text-decoration-style работает только в Firefox, вот скриншот из него:

Чего не хватает

Серия свойств text-decoration-* намного более интуитивна в использовании, чем остальные свойства CSS для оформления подчеркивания. Но если взглянуть внимательнее, то для удовлетворения наших запросов не хватает способов задать толщину или позицию линии.

После небольшого исследования, я нашел еще пару свойств:

  • text-underline-width
  • text-underline-position

Судя по всему, они относятся к ранним черновикам CSS, но их так и не реализовали в браузерах из-за отсутствия интереса.

Дополнительные фишки для подчеркивания ссылок

Начинающие пользователи часто задают некоторые типовые вопросы по теме, поэтому мы также решили их рассмотреть. Общий пример находится в самом низу после пояснений.

Как убрать подчеркивание ссылки

a:hover {
text-decoration: underline;
}

Оба примера ниже позволяют понять логику работы при наведении: или вы изначально указываете в CSS подчеркивание ссылок, а потом убираете его в hover, либо наоборот.

Существует куча разных способов оформления подчеркивания. Возможно, вы вспомните статью Марсина Вичари “Crafting link underlines” на Medium. Разработчики Medium не пытаются сделать что-то безумное , они просто хотят создать красивую линию под текстом.

Это самое простое подчеркивание, но у него правильный размер и оно не перекрывает выносные элементы букв . И оно однозначно лучше дефолтного подчеркивания в большинстве браузеров. Medium пришлось столкнуться со сложностями для достижения своего стиля в вебе. Два года спустя, нам все также сложно сделать красивое подчеркивание.

Подчёркивание ссылок при наведении на них курсора мыши

Чтобы добавить подчёркивание для ссылок, у которых установлено text-decoration: none, следует воспользоваться псевдоклассом :hover. Он определяет стиль ссылки, когда на неё наводится курсор мыши. Остаётся только добавить для псевдокласса свойство text-decoration со значением underline (пример 2).

Пример 2. Подчёркивание ссылок

<!DOCTYPE html>
<html>
<head>
<meta charset=»utf-8″>
<title>Ссылки</title>
<style>
a {
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
</style>
</head>
<body>
<p><a href=»link.html»>Ссылка без подчёркивания</a>
</body>
</html>

Рисунки возле внешних ссылок

Внешней называется такая ссылка, которая указывает на другой сайт. Подобная ссылка никак не отличается от локальных ссылок внутри сайта, определить, куда она ведёт, можно только посмотрев строку состояния браузера. Но в эту строку заглядывают не все и не всегда. Чтобы пользователи отличали внешние ссылки от обычных, их следует выделять каким-либо способом. Например, поставить возле ссылки маленький рисунок, который показывает, что статус ссылки иной (рис. 3).

Рис. 3. Выделение ссылки с помощью рисунка

Использование рисунков возле внешних ссылок хорошо тем, что оформленная таким образом ссылка однозначно отличается от обычных ссылок внутри сайта, а правильно подобранный рисунок говорит посетителю, что ссылка ведёт на другой сайт. Чтобы разделить стиль для локальных и внешних ссылок воспользуемся селектором атрибута. Поскольку все ссылки на другие сайты пишутся с указанием протокола, например http, то достаточно задать стиль для тех ссылок, у которых значение атрибута href начинается на http://. Это делается с помощью конструкции a[href^=»http://»] {…}, как показано в примере 7.

Пример 7. Рисунок возле ссылки

<!DOCTYPE html>
<html>
<head>
<meta charset=»utf-8″>
<title>Ссылки</title>
<style>
a[href^=»http://»] {
background: url(/example/image/blank.png) 100% 5px no-repeat; /* Рисунок */
padding-right: 18px; /* Отступ справа */
}
</style>
</head>
<body>
<p><a href=»1.html»>Обычная ссылка</a></p>
<p><a href=»http://htmlbook.ru»>Ссылка на сайт htmlbook.ru</a></p>
</body>
</html>

Фоновая картинка располагается справа от ссылки, а чтобы текст не накладывался поверх рисунка добавлено поле справа через свойство padding-right. Если потребуется добавить рисунок слева, то 100% заменяем на 0, а padding-right на padding-left.

Протокол может быть не только http, но и ftp и https, для них данный рецепт перестаёт работать. Так что для универсальности лучше изменить селектор на a[href*=»//»], он сообщает что стиль надо применять ко всем ссылкам, в адресе которых встречается //.

ссылки

Подчёркивание текста

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

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

  • Подчёркнутый текст читается хуже, чем обычный. С учётом того, что чтение с экрана по сравнению с чтением с листа бумаги менее комфортно, данный фактор становится важным для повышения удобства восприятия информации.
  • На веб-страницах подчёркивание ссылок стало определённым стандартом. Когда мы видим на сайте подчёркнутый текст, то воспринимаем его в силу привычки как ссылку. Если это не так, возникает раздражение: почему этот текст выглядит как ссылка, но при этом ссылкой не является?

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

Для добавления подчёркивания есть два основных метода. Первый заключается в использовании свойства text-decoration со значением underline, как показано в примере 1.

Пример 1. Свойство text-decoration

<!DOCTYPE html>
<html>
<head>
<meta charset=»utf-8″>
<title>Подчёркивание</title>
<style>
.dot {
text-decoration: underline;
}
</style>
</head>
<body>
<h1 class=»dot»>Часть 4, в которой Пол и
Пропилен наносят ответный удар</h1>
</body>
</html>

Результат данного примера показан на рис. 2. Цвет и толщина такой линии устанавливаются браузером самостоятельно в зависимости от размера и цвета текста и не могут быть изменены через стили. Кстати, это же свойство со значением none применяется для того, чтобы убрать подчёркивание у текста, например, у ссылок.

Рис. 2. Вид линии, полученной с помощью text-decoration

Второй метод позволяет установить линию произвольного стиля и цвета через свойство border-bottom. Например, для добавления пунктирного подчёркивания у ссылок используем значение dashed. Чтобы подчёркивание применялось не ко всем ссылкам, следует указать уникальный класс, назовём его, скажем dot. Также необходимо убрать исходное подчёркивание у ссылок (пример 2).

Пример 2. Пунктирное подчёркивание

<!DOCTYPE html>
<html>
<head>
<meta charset=»utf-8″>
<title>Пунктирное подчёркивание</title>
<style>
a.dot {
text-decoration: none; /* Убираем подчёркивание */
border-bottom
: 1px dashed #000080; /* Добавляем свою линию */
}
</style>
</head>
<body>
<p><a href=»link1.html»>Обычная ссылка</a> на другую страницу.</p>
<p><a href=»link2.html» class=»dot»>Ссылка с пунктирным подчёркиванием</a>.</p>
</body>
</html>

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

Рис. 3. Вид обычной ссылки и ссылки с пунктирным подчёркиванием

Толщина линии и цвет подчёркивания у ссылок также задаются через свойство border-bottom

Обратите внимание на некоторые моменты. Линия, полученная через border-bottom, располагается чуть ниже традиционного подчёркивания

При добавлении такой линии к блочным элементам, вроде

, линия будет не под текстом, а занимать всю ширину элемента.

Визуальное оформление текста в CSS

В CSS оформление текста осуществляется с помощью параметра text-decoration, который может принимать следующие значения:

  • blink — мерцающий текст;
  • none — значение по умолчанию, оформление отсутствует;
  • overline — линия расположена над текстом;
  • underline — подчеркнутый линией текст;
  • line-through — текст, зачеркнутый линией;
  • inherit — в данном случае text-decoration наследует значение родительского элемента.

Пример:

<a href="index.html" style="text-decoration:none">Текст ссылки</a>
<a href="index.html" style="text-decoration:overline">Текст ссылки</a>
<a href="index.html" style="text-decoration:underline">Текст ссылки</a>
<a href="index.html" style="text-decoration:line-through">Текст ссылки</a>
<a href="index.html" style="text-decoration:none">Текст ссылки</a>

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

Possible Values

Specifies what line decorations, if any, are added to the element. The following values are valid:

Neither produces nor inhibits text decoration.
Each line of text is underlined.
Each line of text has a line over it.
Each line of text has a line through the middle.
The text blinks (alternates between visible and invisible). Note that this value is deprecated in favor of CSS animations.
The style of the text decoration.

A solid line.
A wavy line.
A dotted line.
A line consisting of dashes.
A double solid line.
The color of the text decoration. Can be any valid color.

In addition, all CSS properties also accept the following CSS-wide keyword values as the sole component of their property value:

Represents the value specified as the property’s initial value.
Represents the computed value of the property on the element’s parent.
This value acts as either or , depending on whether the property is inherited or not. In other words, it sets all properties to their parent value if they are inheritable or to their initial value if not inheritable.
Добавить комментарий

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

Adblock
detector