- vertical-align
- Синтаксис
- Значения для строчных элементов
- Значения относительно родительского элемента
- Значения относительно строки
- Значения для ячеек таблицы
- Формальный синтаксис
- Пример
- HTML
- CSS
- Результат
- Спецификации
- Совместимость с браузерами
- Смотрите также
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- How to Vertically Center Text with CSS
- Use the CSS vertical-align property
- Example of vertically aligning a text:
- CSS Text Alignment
- Text Alignment
- Example
- Example
- Text Align Last
- Example
- Text Direction
- Example
- Vertical Alignment
- Example
- The CSS Text Alignment/Direction Properties
vertical-align
Свойство CSS vertical-align описывает вертикальное позиционирование строчных (inline), строчно-блочных (inline-block) элементов или ячеек таблицы (table-cell).
/* ключевые значения */ vertical-align: baseline; vertical-align: sub; vertical-align: super; vertical-align: text-top; vertical-align: text-bottom; vertical-align: middle; vertical-align: top; vertical-align: bottom; /* значения длины () */ vertical-align: 10em; vertical-align: 4px; /* процентные значения () */ vertical-align: 20%; /* глобальные значения */ vertical-align: inherit; vertical-align: initial; vertical-align: unset;
Свойство vertical-align может использоваться в двух контекстах:
- Для вертикального позиционирования области строчного элемента внутри области содержащей его строки. Например, с помощью него можно вертикально позиционировать в строке текста:
p> top:img style="vertical-align:top" src="star.png"/> middle:img style="vertical-align:middle" src="star.png"/> bottom:img style="vertical-align:bottom" src="star.png"/> super:img style="vertical-align:super" src="star.png"/> sub:img style="vertical-align:sub" src="star.png"/> p> p> text-top:img style="vertical-align:text-top" src="star.png"/> text-bottom:img style="vertical-align:text-bottom" src="star.png"/> 0.2em:img style="vertical-align:0.2em" src="star.png"/> -1em:img style="vertical-align:-1em" src="star.png"/> 20%:img style="vertical-align:20%" src="star.png"/> -100%:img style="vertical-align:-100%" src="star.png"/> p>
#* box-sizing: border-box; > img margin-right: 0.5em; > p height: 3em; padding: 0 .5em; font-family: monospace; text-decoration: underline overline; margin-left: auto; margin-right: auto; width: 80%; >
table> tr> td style="vertical-align: baseline">baselinetd> td style="vertical-align: top">toptd> td style="vertical-align: middle">middletd> td style="vertical-align: bottom">bottomtd> td> p>Существует теория, которая утверждает, что если однажды кто-нибудь доподлинно выяснит, что такое и для чего нужна Вселенная, она тотчас же исчезнет, и вместо неё появится нечто ещё более причудливое и необъяснимое.p> p>Существует и другая теория, согласно которой это уже случилось.p>
table margin-left: auto; margin-right: auto; width: 80%; > table, th, td border: 1px solid black; > td padding: 0.5em; font-family: monospace; >
Примечание: свойство vertical-align применяется только к строчным элементам и элементам ячеек таблицы: его нельзя использовать для вертикального позиционирования блочных элементов.
Начальное значение | baseline |
---|---|
Применяется к | строчным элементам и ячейкам таблиц. Это также применяется к ::first-letter и ::first-line . |
Наследуется | нет |
Проценты | относятся к line-height самого элемента |
Обработка значения | для процентов и значений длин, абсолютных длин или ключевых слов, если указаны |
Animation type | длина |
Синтаксис
Свойство vertical-align задаётся одним из ключевых значений, указанных ниже.
Значения для строчных элементов
Значения относительно родительского элемента
Данные значения позиционируют элемент по вертикали относительно родительского элемента:
Выравнивает базовую линию элемента с базовой линией родительского элемента. Базовая линия некоторых замещаемых элементов (en-US) , таких как (en-US), не описана в спецификации HTML, что означает, что их поведение при указании данного ключевого слова может отличаться в зависимости от браузера.
Выравнивает базовую линию элемента с базовой линией подстрочного индекса своего родителя.
Выравнивает базовую линию элемента с базовой линией надстрочного индекса своего родителя.
Выравнивает верхний край элемента с верхним краем шрифта родительского элемента.
Выравнивает нижний край элемента с нижним краем шрифта родительского элемента.
Выравнивает середину элемента с базовой линией своего родителя плюс половина от его высоты (x-height).
Поднимает базовую линию элемента на указанную величину над базовой линией родительского элемента. Допустимы отрицательные значения.
Поднимает базовую линию элемента на указанную в процентах величину (вычисляется относительно значения свойства line-height ) над базовой линией родительского элемента. Допустимы отрицательные значения.
Значения относительно строки
Следующие значения позиционируют элемент по вертикали относительно всей строки:
Выравнивает верхний край элемента и его потомков с верхним краем всей строки.
Выравнивает нижний край элемента и его потомков с нижним краем всей строки.
Для элементов, у которых нет базовой линии, вместо неё используется нижняя граница внешнего отступа (margin).
Значения для ячеек таблицы
baseline (и sub , super , text-top , text-bottom ,
Выравнивает базовую линию ячейки с базовой линией всех остальных ячеек этой строки, которые выравнены относительно базовой линии.
Выравнивает верхнюю границу внутреннего отступа (padding) ячейки с верхним краем строки таблицы.
Выравнивает внутреннее поле (padding box) ячейки по центру относительно строки таблицы.
Выравнивает нижнюю границу внутреннего отступа (padding) ячейки с нижним краем строки таблицы.
Допустимы отрицательные значения.
Формальный синтаксис
vertical-align =
[ (en-US) first | (en-US) last ] (en-US) || (en-US)
|| (en-US)
Пример
HTML
div>Изображение img src="frame_image.svg" alt="link" width="32" height="32" /> с выравниванием по умолчанию.div> div>Изображение img class="top" src="frame_image.svg" alt="link" width="32" height="32" /> с выравниванием по верхнему краю.div> div>Изображение img class="bottom" src="frame_image.svg" alt="link" width="32" height="32" /> с выравниванием по нижнему краю.div> div>Изображение img class="middle" src="frame_image.svg" alt="link" width="32" height="32" /> с выравниванием по центру.div>
CSS
img.top vertical-align: text-top; > img.bottom vertical-align: text-bottom; > img.middle vertical-align: middle; >
Результат
Спецификации
Совместимость с браузерами
BCD tables only load in the browser
Смотрите также
Found a content problem with this page?
This page was last modified on 11 февр. 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.
How to Vertically Center Text with CSS
Centering elements vertically with CSS often gives trouble. However, there are several ways of vertical centering, and each is easy to use.
Use the CSS vertical-align property
The vertical-align property is used to vertically center inline elements.
The values of the vertical-align property align the element relative to its parent element:
- Line-relative values vertically align an element relative to the entire line.
- Values for table cells are relative to the table-height-algorithm, which commonly refers to the height of the row.
It is important to note that it is possible to nudge text vertically up or down in CSS using the vertical-align property. This property sets the vertical alignment of an inline or table-cell element, and can be used to adjust the vertical position of text within its container.
Note that vertical-align only applies to inline or table-cell elements, so it may not work as expected on block-level elements such as or
. In such cases, you may need to wrap the text in an inline or table-cell element to apply vertical-align .
Example of vertically aligning a text:
html> html> head> title>Title of the document title> style> div < display: table-cell; width: 250px; height: 200px; padding: 10px; border: 3px dashed #1c87c9; vertical-align: middle; > style> head> body> div>Vertically aligned text div> body> html>
CSS Text Alignment
In this chapter you will learn about the following properties:
- text-align
- text-align-last
- direction
- unicode-bidi
- vertical-align
Text Alignment
The text-align property is used to set the horizontal alignment of a text.
A text can be left or right aligned, centered, or justified.
The following example shows center aligned, and left and right aligned text (left alignment is default if text direction is left-to-right, and right alignment is default if text direction is right-to-left):
Example
When the text-align property is set to «justify», each line is stretched so that every line has equal width, and the left and right margins are straight (like in magazines and newspapers):
Example
Text Align Last
The text-align-last property specifies how to align the last line of a text.
Example
Align the last line of text in three
elements:
Text Direction
The direction and unicode-bidi properties can be used to change the text direction of an element:
Example
Vertical Alignment
The vertical-align property sets the vertical alignment of an element.
Example
Set the vertical alignment of an image in a text:
img.a <
vertical-align: baseline;
>
img.b vertical-align: text-top;
>
img.c vertical-align: text-bottom;
>
The CSS Text Alignment/Direction Properties
Property | Description |
---|---|
direction | Specifies the text direction/writing direction |
text-align | Specifies the horizontal alignment of text |
text-align-last | Specifies how to align the last line of a text |
unicode-bidi | Used together with the direction property to set or return whether the text should be overridden to support multiple languages in the same document |
vertical-align | Sets the vertical alignment of an element |