How to vertically center text with css
Содержание:
- Как выровнять текст по центру при помощи CSS?
- Пример использования
- Определение и применение
- CSS Reference
- CSS Properties
- CSS Properties
- Выравнивание элементов. align-items и align-self
- Property Values
- CSS horizontal align
- 15.2 Fonts
- Выравнивание текста с помощью CSS
- CSS Справочники
- CSS Свойства
- CSS Reference
- CSS Properties
Как выровнять текст по центру при помощи CSS?
Лично я считаю, что использовать теги и атрибуты HTML для выравнивания текста по центру – это не самое правильное решение. Если вам нужно выровнять текст только в одном-двух местах и неохота лезть в CSS, то можно обойтись возможностями HTML, но для выравнивания по центру в нескольких местах на странице лучше использовать CSS.
Для этого у нас есть специальное свойство text-align, которое так же имеет несколько значений:
- text-align: center; — для выравнивания по центру
- text-align: left; — по левой стороне
- text-align: right; — по правой стороне
- text-align: justify; — по ширине блока или страницы.
Для того чтобы его применить к нашему тексту можно воспользоваться одним из предложенных вариантов:
-
1.Присвоить тегу блока (заголовка, формы, абзаца или другому блочному элементу) CSS класс:
PHP
<div class=”block-text”>Здесь текст</div>
1 <div class=”block-text”>Здесьтекст<div> А затем в CSS файле вашего сайта пишем:
PHP
.block-text {
text-align: center;
}1
2
3.block-text{
text-aligncenter;
}
Вместо block-text может быть любое другое название класса.
Также можно не присваивать новый класс, а использовать уже существующий. В этой статье с видео инструкцией я показывала как определить класс или идентификатор элемента на сайте: “Как определить ID и класс элемента на странице?”
Если вам нужно сделать выравнивание текста по центру сразу для всех абзацев или заголовков на сайте, то не обязательно для каждого писать это CSS свойство. Достаточно задать или определить класс или идентификатор блока, внутри которого находятся эти абзацы или заголовки, а дальше в CSS файле добавить такую запись:
PHP
.block p {
text-align: center;
}1
2
3.blockp{
text-aligncenter;
}
В этом случае выравнивание текста по центру применится для всех тегов
, которые находятся внутри тега с классом block:
PHP
<div class=”block”>
<p>Первый абзац</p>
<p>Второй абзац</p>
….
</div>1
2
3
4
5<div class=”block”>
<p>Первыйабзац<p>
<p>Второйабзац<p>
….
<div>
Для выравнивания заголовков внутри блока с классом block запись будет немного другая:
PHP
.block h1, .block h2, .block h3, .block h4, .block h5, .block h6 {
text-align: center;
}1
2
3.block h1,.block h2,.block h3,.block h4,.block h5,.block h6{
text-aligncenter;
}
Так же вы можете задать эти CSS свойства в HTML коде страницы или подключить свой отдельный CSS файл. Как это сделать написано в этой статье:«Как css подключить к html?»
-
2.Можно дописать нужные CSS свойства в самом теге при помощи атрибута style:
PHP
<p style=” text-align: center;”>Пример текста</p>
1 <pstyle=”text-aligncenter;”>Примертекста<p> Этот способ, так же как и атрибут align или тег center, удобен только в тех случаях, когда выравнивание нужно сделать в одном или нескольких местах. Для массового выравнивания текста я его не рекомендую использовать.
Описанные выше способы помогут вам выровнять по центру текст. Так же вам могут понадобиться вот эти материалы:«Как выровнять текст или блок по вертикали в CSS?»«Выравнивание картинки по центру HTML и CSS»
На этом у меня всё! Спасибо что посетили мой сайт! Буду очень рада видеть ваши комментарии! Успехов вам и процветания!
С уважением Юлия Гусарь
Пример использования
<!DOCTYPE html>
<html>
<head>
<title>Вертикальное позиционирование.</title>
<style>
div {
width : 30%; /* задаём ширину блока */
}
img {
width : 75px; /* задаём ширину изображения */
height : 75px; /* задаём высоту изображения */
}
p {
background-color : orange; /* задаём задний фон для элемента <p> */
}
.top {
vertical-align : text-top; /* верх элемента выравнивается с верхом шрифта родительского элемента */
}
.bottom {
vertical-align : text-bottom; /* низ элемента выравнивается с низом шрифта родительского элемента */
}
</style>
</head>
<body>
<p>Baseline<img src = "nich.jpg" alt = "nich"></p>
<p>Text-Top<img src = "nich.jpg" alt = "nich" class = "top"></p>
<p>Text-Bottom<img src = "nich.jpg" alt = "nich" class = "bottom"></p>
</body>
</html>

Пример вертикального позиционирования.CSS свойства
Определение и применение
CSS свойство align-content определяет как браузер распределяет пространство между и вокруг флекс элементов вдоль поперечной оси контейнера (вертикально), или производит выравнивание всего макета сетки по оси столбца grid-контейнера.
Для того, чтобы определить как браузер распределяет пространство между и вокруг флекс элементов вдоль главной оси контейнера (горизонтально), или производит выравнивание всего макета сетки по оси строки grid-контейнера, вы можете воспользоваться свойством justify-content.
При работе с флекс элементами обратите внимание на то, что свойство align-content возможно применить только к многострочным флекс контейнерам (flex-wrap, или flex-flow со значениями wrap | wrap-reverse). Если элемент не является флекс элементом, или элементом сетки макета (не находится внутри родительского элемента, который является блочным, или строчным флекс, или grid-контейнером), то свойство align-content не окажет на такой элемент никакого эффекта
Если элемент не является флекс элементом, или элементом сетки макета (не находится внутри родительского элемента, который является блочным, или строчным флекс, или grid-контейнером), то свойство align-content не окажет на такой элемент никакого эффекта.
Более подробную информацию о работе с флекс элементами вы можете получить в статье учебника CSS «Верстка по Flexbox (работа с контейнерами)».
Схематичное отображение работы свойства align-content отображено на следующем изображении:
* — для элементов сетки макета (grid-элементы) допускается использование сокращенных значений start и end, для флекс элементов необходимо использовать полные значения flex-start и flex-end.
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
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
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
CSS Properties
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-sizingbreak-afterbreak-beforebreak-insidecaption-sidecaret-color@charsetclearclipclip-pathcolorcolumn-countcolumn-fillcolumn-gapcolumn-rulecolumn-rule-colorcolumn-rule-stylecolumn-rule-widthcolumn-spancolumn-widthcolumnscontentcounter-incrementcounter-resetcursordirectiondisplayempty-cellsfilterflexflex-basisflex-directionflex-flowflex-growflex-shrinkflex-wrapfloatfont@font-facefont-familyfont-feature-settingsfont-kerningfont-sizefont-size-adjustfont-stretchfont-stylefont-variantfont-variant-capsfont-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-eventspositionquotesresizerightscroll-behaviortab-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
Выравнивание элементов. align-items и align-self
Последнее обновление: 18.04.2017
Свойство align-items
Свойство align-items также выравнивает элементы, но уже по поперечной оси (cross axis) (при расположении в виде строки по вертикали, при расположении в виде столбца — по горизонтали).
Это свойство может принимать следующие значения:
-
stretch: значение по умолчанию, при котором flex-элементы растягиваются по всей высоте (при расположении в строку) или по всей ширине
(при расположении в столбик) flex-контейнера -
flex-start: элементы выравниваются по верхнему краю (при расположении в строку) или по левому краю
(при расположении в столбик) flex-контейнера -
flex-end: элементы выравниваются по нижнему краю (при расположении в строку) или по правому краю
(при расположении в столбик) flex-контейнера -
center: элементы выравниваются по центру flex-контейнера
-
baseline: элементы выравниваются в соответствии со своей базовой линией
Выравнивание при расположении в строку:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Flexbox в CSS3</title>
<style>
.flex-container {
display: flex;
border:1px #ccc solid;
height:5em;
}
.flex-start{
align-items: flex-start;
}
.flex-end{
align-items: flex-end;
}
.center{
align-items: center;
}
.baseline{
align-items: baseline;
}
.flex-item {
text-align:center;
font-size: 1em;
padding: 1.2em;
color: white;
}
.largest-item{
padding-top:2em;
}
.color1 {background-color: #675BA7;}
.color2 {background-color: #9BC850;}
.color3 {background-color: #A62E5C;}
.color4 {background-color: #2A9FBC;}
</style>
</head>
<body>
<h3>Flex-start</h3>
<div class="flex-container flex-start">
<div class="flex-item color1">Flex Item 1</div>
<div class="flex-item color2">Flex Item 2</div>
<div class="flex-item color3">Flex Item 3</div>
<div class="flex-item color4">Flex Item 4</div>
</div>
<h3>Flex-end</h3>
<div class="flex-container flex-end">
<div class="flex-item color1">Flex Item 1</div>
<div class="flex-item color2">Flex Item 2</div>
<div class="flex-item color3">Flex Item 3</div>
<div class="flex-item color4">Flex Item 4</div>
</div>
<h3>Center</h3>
<div class="flex-container center">
<div class="flex-item color1">Flex Item 1</div>
<div class="flex-item color2">Flex Item 2</div>
<div class="flex-item color3">Flex Item 3</div>
<div class="flex-item color4">Flex Item 4</div>
</div>
<h3>Baseline</h3>
<div class="flex-container baseline">
<div class="flex-item color1">Flex Item 1</div>
<div class="flex-item color2 largest-item">Flex Item 2</div>
<div class="flex-item color3">Flex Item 3</div>
<div class="flex-item color4">Flex Item 4</div>
</div>
</html>
Аналогично свойство работает при расположении в столбик. Например, изменим стили flex-контейнера следующим образом:
.flex-container {
display: flex;
border:1px #ccc solid;
flex-direction:column;
width:12em;
}
Свойство align-self
Свойство align-self позволяет переопределить значение свойства для одного элемента.
Оно может принимать все те же значения плюс значение «auto»:
-
auto: значение по умолчанию, при котором элемент получает значение от свойства , которое определено
в flex-контейнере. Если в контейнере такой стиль не определен, то применяется значение . -
stretch
-
flex-start
-
flex-end
-
center
-
baseline
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Flexbox в CSS3</title>
<style>
.flex-container {
display: flex;
border:1px #ccc solid;
justify-content: space-between;
align-items: stretch;
height:12em;
}
.flex-item {
text-align:center;
font-size: 1em;
padding: 1.2em;
color: white;
}
.item1 {background-color: #675BA7; align-self: center; }
.item2 {background-color: #9BC850; align-self: flex-start;}
.item3 {background-color: #A62E5C; align-self: flex-end;}
.item4 {background-color: #2A9FBC; align-self: center;}
</style>
</head>
<body>
<h3>Align-self</h3>
<div class="flex-container">
<div class="flex-item item1">Flex Item 1</div>
<div class="flex-item item2">Flex Item 2</div>
<div class="flex-item item3">Flex Item 3</div>
<div class="flex-item item4">Flex Item 4</div>
</div>
</html>
Здесь для flex-контейнера задано растяжение по высоте с помощью значения . Однако каждый из элементов переопределяет это поведение:
НазадВперед
Property Values
| Value | Description | Play it |
|---|---|---|
| auto | Default. The element inherits its parent container’s align-items property, or «stretch» if it has no parent container | Play it » |
| stretch | The element is positioned to fit the container | Play it » |
| center | The element is positioned at the center of the container | Play it » |
| flex-start | The element is positioned at the beginning of the container | Play it » |
| flex-end | The element is positioned at the end of the container | Play it » |
| baseline | The element is positioned at the baseline of the container | Play it » |
| initial | Sets this property to its default value. Read about initial | Play it » |
| inherit | Inherits this property from its parent element. Read about inherit |
CSS horizontal align
Aligning inline elements
and text are the easiest to align. You can do that by using the text-align property:
Example Copy
This property can take one of six possible values:
| Value | Syntax | Description |
|---|---|---|
| The default value. Makes CSS center the element in the container | ||
| Makes CSS align the element at the left side of the container | ||
| Makes CSS align the element at the right side of the container | ||
| Makes CSS space the content to fill the container from edge to edge | ||
| Works like when the text direction is left-to-right and like when it’s right-to-left | ||
| Works like when the text direction is left-to-right and like when it’s right-to-left |
Using margins for block elements
To make CSS center or otherwise align a , set both its left and right margins to . See how to center div elements in the example below:
Example Copy
To be able to do the same to any element, you can apply a property with its value set to to it. For example, to center an image horizontally, you would follow the example below:
Example Copy
Modifying position
If you only have one element in the container, you can also align it horizontally by using the position property. If you define the value, the position will be fixed, which means that the element may overlap other elements to keep its particular place when a user resizes the window or scrolls:
Example Copy
Making elements float
You can also align elements using the property:
Example Copy
The property is different from absolute position in two aspects. First, it places an element on the specified side of the container so that text and other inline elements can wrap around it.
Secondly, the floated element is removed from the normal flow of the page. However, it does remain a part of the flow in a sense that other elements don’t ignore it completely (which they do for absolutely positioned elements).
When you float an image or another element that has a bigger height than its container, such element overflows the boundaries of the container. You can prevent this by applying the overflow property with its value set to :
Example Copy
Pros
- Simplistic design (no unnecessary information)
- High-quality courses (even the free ones)
- Variety of features
Main Features
- Nanodegree programs
- Suitable for enterprises
- Paid certificates of completion
100% FREE
Pros
- Professional service
- Flexible timetables
- A variety of features to choose from
Main Features
- Professional certificates of completion
- University-level courses
- Multiple Online degree programs
100% FREE
Pros
- Great user experience
- Offers quality content
- Very transparent with their pricing
Main Features
- Free certificates of completion
- Focused on data science skills
- Flexible learning timetable
100% FREE
15.2 Fonts
The following HTML elements specify font information. Although they are
not all , their use is
discouraged in favor of style sheets.
15.2.1 Font style elements:
the TT, I, B,
BIG,
SMALL,
STRIKE, S, and U elements
<!ENTITY % fontstyle
" | | | | ">
<!ELEMENT (|) - - ()*>
<!ATTLIST (|)
-- , , --
>
Start tag: required, End tag:
required
Attributes defined elsewhere
- , ()
- (), ()
- ()
- ()
- , , , , , , , , ()
Rendering of font style elements depends on the user agent. The following is
an informative description only.
- TT: Renders as teletype or monospaced text.
- I: Renders as italic text style.
- B: Renders as bold text style.
- BIG: Renders text in a «large» font.
- SMALL: Renders text in a «small» font.
- STRIKE and S: Render strike-through style text.
- U: Renders underlined text.
The following sentence shows several types of text:
<P><b>bold</b>, <i>italic</i>, <b><i>bold italic</i></b>, <tt>teletype text</tt>, and <big>big</big> and <small>small</small> text.
These words might be rendered as follows:

It is possible to achieve a much richer variety of font effects using style
sheets. To specify blue, italic text in a paragraph with CSS:
<HEAD>
<STYLE type="text/css">
P#mypar {font-style: italic; color: blue}
</STYLE>
</HEAD>
<P id="mypar">...Lots of blue italic text...
Font style elements must be properly nested. Rendering of nested font style
elements depends on the user agent.
15.2.2 Font modifier
elements: FONT and BASEFONT
and are .
See the for
the formal definition.
Attribute definitions
- size =
-
This
attribute sets the size of the font. Possible values:- An integer between 1 and 7. This sets the font to some fixed size, whose
rendering depends on the user agent. Not all user agents may render all seven
sizes. - A relative increase in font size. The value «+1» means one size larger. The
value «-3» means three sizes smaller. All sizes belong to the scale of 1 to
7.
- An integer between 1 and 7. This sets the font to some fixed size, whose
- color =
-
This
attribute sets the text color. - face =
-
This
attribute defines a comma-separated list of font names the user agent should
search for in order of preference.
Attributes defined elsewhere
- , ()
- (), ()
- ()
- ()
The element changes the font size and color for text in its
contents.
The element sets the base font size (using the size attribute). Font size changes achieved with
are relative to the base font size set by . If is not used, the default base font size is 3.
DEPRECATED EXAMPLE:
The following example will show the difference between the seven font sizes
available with :
<P><font size=1>size=1</font> <font size=2>size=2</font> <font size=3>size=3</font> <font size=4>size=4</font> <font size=5>size=5</font> <font size=6>size=6</font> <font size=7>size=7</font>
This might be rendered as:
The following shows an example of the effect of relative font sizes using a
base font size of 3:

The base font size does not apply to headings, except where these are
modified using the element with a relative font size change.
Выравнивание текста с помощью CSS
Начнем с атрибутов стиля, управляющих выводом текста в блочных элементах. Начнем со свойства text-align, которое является фактически заменой атрибута align (используется для выравнивания содержимого html-элементов, например абзацев p).
Свойство стиля text-align задает горизонтальное выравнивание текста и имеет всего четыре возможных значения:
Доступные значения этого правила определяют выравнивание, соответственно: left — по левому краю, right — по правому краю, center — по центру и justify — по ширине страницы (одновременно по левому и правому краю за счет увеличения расстояния между словами). Для примера, текст этой статьи выравнен по ширине страницы (если вы заметили у него ровные границы и слева и справа) с помощью правила text-align:justify.
По умолчанию, горизонтальное выравнивание выполняется по левому краю, поэтому специально указывать text-align:left не обязательно, если в родительских элементах не было указано другого выравнивания.
Примеры использования свойства:
Следующее свойство CSS text-ident задает отступ для красной строки, например для текста в теге абзаца p. Это правило также, как и text-align, применимо только для блочных элементов. Синтаксис:
Здесь допускаются абсолютные и относительные величины отступа. Абсолютные значения (px — пикселы, em, ex и др.) можно указывать как со знаком плюс, так и со знаком минус. Относительная величина обычно задается в процентах (%). Относительное значение рассчитывается от ширины области, которая отведена под текст. Так, css правило text-indent:50% задаст красную строку равную половине длины этой самой строки. По умолчанию отступ «красной строки» равен нулю. Пример:
Далее рассмотрим вертикальное выравнивание — свойство vertical-align. Это свойство применимо уже для всех html элементов и практически для всех означает выравнивание между собой строчных элементов с текстом относительно их базовой линии. Кроме тегов таблицы td и th, в которых по вертикали будет выравниваться весь контент. Синтаксис:
Рассмотрим каждое значение подробнее:
- baseline — выравнивание фрагмента текста по базовой линии родительского элемента. Это значение по умолчанию;
- sub — фрагмент текста изображается в виде нижнего индекса или подстрочным для родительского элемента;
- super — фрагмент текста изображается в виде верхнего индекса или надстрочным для родительского элемента;
- top — выравнивание фрагмента текста по верхнему краю родительского элемента;
- text-top — выравнивание фрагмента по верхнему краю текста родительского элемента;
- middle — выравнивание центра фрагмента текста по центру родительского элемента;
- bottom — выравнивание фрагмента текста по нижнему краю родительского элемента;
- text-bottom — выравнивание фрагмента по нижнему краю текста родительского элемента;
На рисунке ниже можно посмотреть поведение фрагментов теста при различных значениях свойства vertical-align в браузере Internet Explorer 11:
Кроме вышеперечисленных значений, можно указывать числовые значения. Так, правило CSS vertical-align:0 будет означать тоже самое, что и запись vertical-align:baseline. А правило vertical-align:10px будет смещать текст вверх на 10 пикселей относительно базовой линии. Для смещения текста вниз значение необходимо указывать с минусом.
Сдвиг также можно задавать в относительных единицах измерения, например в em и в ex или в процентах.
Для вертикального выравнивания содержимого ячеек таблицы в vertical-align следует использовать значения:
- top — для выравнивания содержимого по верхней границе ячейки;
- bottom — для выравнивания содержимого по нижней границе ячейки;
- middle — для выравнивания по центру ячейки (используется по умолчанию).
Для достижения нужного результата, обычно приходится экспериментировать с различными значениями свойства стиля vertical-align. Многочисленные возможные значения дают слишком разный результат в различных случаях.
CSS Справочники
CSS СправочникCSS ПоддержкаCSS СелекторыCSS ФункцииCSS ЗвукCSS Веб шрифтыCSS АнимацииCSS ДлиныCSS Конвертер px-emCSS Названия цветаCSS Значения цветаCSS по умолчаниюCSS Символы
CSS Свойства
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
caption-side
caret-color
@charset
clear
clip
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-kerning
font-size
font-size-adjust
font-stretch
font-style
font-variant
font-weight
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
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
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
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
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



