- vertical-align
- Синтаксис
- Значения для строчных элементов
- Значения относительно родительского элемента
- Значения относительно строки
- Значения для ячеек таблицы
- Формальный синтаксис
- Пример
- HTML
- CSS
- Результат
- Спецификации
- Совместимость с браузерами
- Смотрите также
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- CSS Table Alignment
- Example
- Vertical Alignment
- Example
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
- How to center a table with CSS (horizontal and vertical)
- Center table horizontally
- Center table vertically
- Center table vertically and horizontally
- Conclusion
- Learn JavaScript for Beginners 🔥
- About
- Search
- Tags
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.
CSS Table Alignment
To left-align the content, force the alignment of elements to be left-aligned, with the text-align: left property:
Firstname | Lastname | Savings |
---|---|---|
Peter | Griffin | $100 |
Lois | Griffin | $150 |
Joe | Swanson | $300 |
Example
Vertical Alignment
Firstname | Lastname | Savings |
---|---|---|
Peter | Griffin | $100 |
Lois | Griffin | $150 |
Joe | Swanson | $300 |
Example
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
How to center a table with CSS (horizontal and vertical)
The CSS style to center a table differs depending on whether you want the table to be centered horizontally or vertically.
Center table horizontally
To center a table horizontally, you need to set the margin-left and margin-right properties to auto .
It’s recommended that you create a class that applies the CSS style so that it won’t affect all of your tables. Here is an example of how to do this:
Add that class to your table as follows:
Alternatively, you can also define a single margin property and set the value to 0 auto like this:
The margins on top and bottom will be set to 0 while the left and right margins will be set to auto .Center table vertically
To center the table vertically on the browser, you need to make use of CSS Flexbox layout and create a container element for the table (like a ).
The container element must also have a fixed height property for the vertical centering to work.
First, you need to write the CSS for the container as follows:
The height property of the container must be higher than the table, or the centering won’t work.
Add that CSS to the element that contains your table as shown below:
You will see the table rendered in the center vertically like this:
Center table vertically and horizontally
If you want the table to be centered vertically and horizontally, add justify-content: center; property to the flex-center class:
With that property, the table will be centered horizontally and vertically inside the as follows:
Conclusion
To conclude, centering a table with CSS can be done vertically or horizontally, or both.
You can use the CSS styles shown in this tutorial to help you achieve the desired output.
Another element that you might want to center a lot is a button, so I also created a guide on centering button elements with CSS.
You might want to check it out.
Learn JavaScript for Beginners 🔥
Get the JS Basics Handbook, understand how JavaScript works and be a confident software developer.
A practical and fun way to learn JavaScript and build an application using Node.js.
About
Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.
Search
Type the keyword below and hit enter
Tags
Click to see all tutorials tagged with: