- Выравнивание элементов
- Центрирование по вертикали
- Выравнивание по горизонтали
- Выравнивание по верхнему краю
- Выравнивание по центру
- Выравнивание элементов формы
- CSS Table Alignment
- Example
- Vertical Alignment
- Example
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
- How to Center the Text in the HTML Table Row
- Create HTML
- Add CSS
- Example of centering the text in table row using the CSS text-align property:
- Result
- Example of centering the text in table row using the style attributes:
- Example of centering only elements:
- Center a table with CSS
- Method 1
- Method 2
- Method 3
- Center a table with CSS
- Method 1
- Method 2
- Method 3
Выравнивание элементов
За счет того, что содержимое ячеек таблицы можно одновременно выравнивать по горизонтали и вертикали, расширяются возможности по управлению положением элементов относительно друг друга. Таблицы позволяют задавать выравнивание изображений, текста, полей формы и других элементов относительно друг друга и веб-страницы в целом. Вообще, выравнивание в основном необходимо для установки зрительной связи между разными элементами, а также их группирования.
Центрирование по вертикали
Одним из способов показать посетителю направленность и название сайта является использование сплэш-страницы. Это первая страница, на которой, как правило, расположена flash-заставка или рисунок, выражающий главную идею сайта. Изображение также является и ссылкой на остальные разделы сайта. Требуется поместить этот рисунок по центру окна браузера вне зависимости от разрешения монитора. Для этой цели можно воспользоваться таблицей с шириной и высотой равной 100% (пример 1).
Пример 1. Центрирование рисунка

Чтобы высота таблицы устанавливалась как 100%, необходимо убрать , код при этом перестает быть валидным.
Использование ширины и высоты на всю доступную область веб-страницы гарантирует, что содержимое таблицы будет выравниваться строго по центру окна браузера, независимо от его размеров.
Выравнивание по горизонтали
Рис. 1. Выравнивание элементов по горизонтали
Рассмотрим некоторые примеры выравнивания текста согласно приведенному рисунку.
Выравнивание по верхнему краю
Пример 2. Использование valign
Колонка 1 Колонка 2
Пример 3. Применение стилей для выравнивания
Для сокращения кода в данном примере используется группирование селекторов, поскольку свойства vertical-align и padding применяются одновременно к двум ячейкам.
Выравнивание по нижнему краю делается аналогично, только вместо значения top используется bottom .
Выравнивание по центру
По умолчанию содержимое ячейки выравнивается по центру их вертикали, поэтому в случае разной высоты колонок требуется задавать выравнивание по верхнему краю. Иногда все-таки нужно оставить исходный способ выравнивания, например, при размещении формул, как показано на рис. 2.
Рис. 2. Добавление формулы в документ
В подобном случае формула располагается строго по центру окна браузера, а ее номер — по правому краю. Для такого размещения элементов понадобится таблица с тремя ячейками. Крайние ячейки должны иметь одинаковые размеры, в средней ячейке выравнивание делается по центру, а в правой — по правому краю (пример 4). Такое количество ячеек требуется для того, чтобы обеспечить позиционирование формулы по центру.
Пример 4. Выравнивание формулы

(18.6)
В данном примере первая ячейка таблицы оставлена пустой, она служит лишь для создания отступа, который, кстати, может быть установлен и с помощью стилей.
Выравнивание элементов формы
С помощью таблиц удобно определять положение полей формы, особенно, когда они перемежаются с текстом. Один из вариантов оформления формы, которая предназначена для ввода комментария, показан на рис. 3.
Рис 3. Расположение полей формы и текста
Чтобы текст возле полей формы был выровнен по правому краю, а сами элементы формы — по левому, потребуется таблица с невидимой границей и двумя колонками. В левой колонке будет размещаться собственно текст, а в правой текстовые поля (пример 5).
Пример 5. Выравнивание полей формы
В данном примере, для тех ячеек, где требуется задать выравнивание по правому краю, добавлен атрибут align=»right» . Чтобы надпись «Комментарий» располагалась по верхней границе многострочного текста, для соответствующей ячейки устанавливается выравнивание по верхнему краю с помощью атрибута valign .
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 the Text in the HTML Table Row
Earlier, it was possible to do this using the align attribute, however, it is deprecated in HTML5. Instead of using that attribute, use the CSS text-align property, or specify it through the inline style attributes.
In this snippet, we’ll show and explain examples with the text-align property and style attribute.
Create HTML
table> tr> td>Text td> td>Text td> tr> tr> td>Text td> td>Text td> tr> table>
Add CSS
table, table td < border: 1px solid #cccccc; > td < height: 80px; width: 160px; text-align: center; vertical-align: middle; >
Now, you can see the full example.
Example of centering the text in table row using the CSS text-align property:
html> html> head> style> table, table td < border: 1px solid #cccccc; > td < height: 80px; width: 160px; text-align: center; vertical-align: middle; > style> head> body> table> tr> td>Text td> td>Text td> tr> tr> td>Text td> td>Text td> tr> table> body> html>
Result
In our next example, we specify the text-align and vertical-align properties through the style inline attribute.
Example of centering the text in table row using the style attributes:
html> html> head> style> td < height: 80px; width: 160px; > style> head> body> table border="1"> tr> td style="text-align: center; vertical-align: middle;">Text td> td style="text-align: center; vertical-align: middle;">Text td> tr> tr> td style="text-align: center; vertical-align: middle;">Text td> td style="text-align: center; vertical-align: middle;">Text td> tr> table> body> html>
The style attribute overrides the styles set globally. It will override any style set in the tag or external style sheet.
Example of centering only elements:
html> html> head> style> table, table th, td < border: 1px solid #cccccc; border-collapse: collapse; > th, td < height: 80px; width: 160px; padding: 5px 10px; vertical-align: middle; > th < text-align: right; > td < text-align: center; > style> head> body> table> thead> tr> th>Heading th> th>Heading th> tr> thead> tbody> tr> td>Text td> td>Text td> tr> tr> td>Text td> td>Text td> tr> tr> td>Text td> td>Text td> tr> tbody> table> body> html>
Center a table with CSS
The «align» attribute has been deprecated, however, in favor of CSS (Cascading Style Sheets), and this is a good thing. However, it’s not so obvious how to center a table using CSS.
The obvious way might appear to use the CSS «text-align: center;» somewhere, maybe like one of these:
OR, if you get really desperate,
None of these will work. The table itself will be left-aligned, but all the content in the table cells will be centered.
Why? Because «text-align» applies to inline content, not to a block-level element like «table».
Method 1
To center a table, you need to set the margins, like this:
table.center { margin-left:auto; margin-right:auto; }
At this point, Mozilla and Opera will center your table. Internet Explorer 5.5 and up, however, needs you to add this to your CSS as well:
Method 2
If you want your table to be a certain percentage width, you can do this:
table#table1 { width:70%; margin-left:15%; margin-right:15%; }
And then in your HTML/XHTML, you would do this:
Note that I was using an id to describe the table. You can only use an id once on a page. If you had many tables on a page that you wanted to be the same width and centered, you would do this in your CSS:
table.center { width:70%; margin-left:15%; margin-right:15%; }
Method 3
If you want your table to be of fixed width, define your CSS like this:
div.container { width:98%; margin:1%; } table#table1 { text-align:center; margin-left:auto; margin-right:auto; width:100px; } tr,td {text-align:left;}
Set «width:100px» to whatever width you need.
«text-align: center» is there for Internet Explorer, which won’t work without it. Unfortunately, «text-align: center» will center all the text inside your table cells, but we counter that by setting «tr» and «td» to align left.
In your HTML, you would then do this:
Once again, I’m using an id. If you need to center several tables the same way, use a class instead of an id.
Center a table with CSS
The «align» attribute has been deprecated, however, in favor of CSS (Cascading Style Sheets), and this is a good thing. However, it’s not so obvious how to center a table using CSS.
The obvious way might appear to use the CSS «text-align: center;» somewhere, maybe like one of these:
OR, if you get really desperate,
None of these will work. The table itself will be left-aligned, but all the content in the table cells will be centered.
Why? Because «text-align» applies to inline content, not to a block-level element like «table».
Method 1
To center a table, you need to set the margins, like this:
table.center { margin-left:auto; margin-right:auto; }
At this point, Mozilla and Opera will center your table. Internet Explorer 5.5 and up, however, needs you to add this to your CSS as well:
Method 2
If you want your table to be a certain percentage width, you can do this:
table#table1 { width:70%; margin-left:15%; margin-right:15%; }
And then in your HTML/XHTML, you would do this:
Note that I was using an id to describe the table. You can only use an id once on a page. If you had many tables on a page that you wanted to be the same width and centered, you would do this in your CSS:
table.center { width:70%; margin-left:15%; margin-right:15%; }
Method 3
If you want your table to be of fixed width, define your CSS like this:
div.container { width:98%; margin:1%; } table#table1 { text-align:center; margin-left:auto; margin-right:auto; width:100px; } tr,td {text-align:left;}
Set «width:100px» to whatever width you need.
«text-align: center» is there for Internet Explorer, which won’t work without it. Unfortunately, «text-align: center» will center all the text inside your table cells, but we counter that by setting «tr» and «td» to align left.
In your HTML, you would then do this:
Once again, I’m using an id. If you need to center several tables the same way, use a class instead of an id.