Выравнивание

Выравнивание элементов

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

Центрирование по вертикали

Одним из способов показать посетителю направленность и название сайта является использование сплэш-страницы. Это первая страница, на которой, как правило, расположена flash-заставка или рисунок, выражающий главную идею сайта. Изображение также является и ссылкой на остальные разделы сайта. Требуется поместить этот рисунок по центру окна браузера вне зависимости от разрешения монитора. Для этой цели можно воспользоваться таблицей с шириной и высотой равной 100% (пример 1).

Пример 1. Центрирование рисунка

       
Рецепты HTML

Чтобы высота таблицы устанавливалась как 100%, необходимо убрать , код при этом перестает быть валидным.

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

Читайте также:  Click on menu css

Выравнивание по горизонтали

Рис. 1. Выравнивание элементов по горизонтали

Рассмотрим некоторые примеры выравнивания текста согласно приведенному рисунку.

Выравнивание по верхнему краю

Пример 2. Использование valign

       
Колонка 1 Колонка 2

Пример 3. Применение стилей для выравнивания

        

Для сокращения кода в данном примере используется группирование селекторов, поскольку свойства vertical-align и padding применяются одновременно к двум ячейкам.

Выравнивание по нижнему краю делается аналогично, только вместо значения top используется bottom .

Выравнивание по центру

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

Рис. 2. Добавление формулы в документ

Рис. 2. Добавление формулы в документ

В подобном случае формула располагается строго по центру окна браузера, а ее номер — по правому краю. Для такого размещения элементов понадобится таблица с тремя ячейками. Крайние ячейки должны иметь одинаковые размеры, в средней ячейке выравнивание делается по центру, а в правой — по правому краю (пример 4). Такое количество ячеек требуется для того, чтобы обеспечить позиционирование формулы по центру.

Пример 4. Выравнивание формулы

       
Формула 18.6 (18.6)

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

Выравнивание элементов формы

С помощью таблиц удобно определять положение полей формы, особенно, когда они перемежаются с текстом. Один из вариантов оформления формы, которая предназначена для ввода комментария, показан на рис. 3.

Рис 3. Расположение полей формы и текста

Рис 3. Расположение полей формы и текста

Чтобы текст возле полей формы был выровнен по правому краю, а сами элементы формы — по левому, потребуется таблица с невидимой границей и двумя колонками. В левой колонке будет размещаться собственно текст, а в правой текстовые поля (пример 5).

Пример 5. Выравнивание полей формы

       
Имя E-mail Комментарий

В данном примере, для тех ячеек, где требуется задать выравнивание по правому краю, добавлен атрибут 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

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

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.

Источник

vertical-align

The vertical-align CSS property sets vertical alignment of an inline, inline-block or table-cell box.

Try it

The vertical-align property can be used in two contexts:

  • To vertically align an inline-level element’s box inside its containing line box. For example, it could be used to vertically position an image in a line of text.
  • To vertically align the content of a cell in a table.

Note that vertical-align only applies to inline, inline-block and table-cell elements: you can’t use it to vertically align block-level elements.

Syntax

/* Keyword values */ 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; /* values */ vertical-align: 10em; vertical-align: 4px; /* values */ vertical-align: 20%; /* Global values */ vertical-align: inherit; vertical-align: initial; vertical-align: revert; vertical-align: revert-layer; vertical-align: unset; 

The vertical-align property is specified as one of the values listed below.

Values for inline elements

Parent-relative values

These values vertically align the element relative to its parent element:

Aligns the baseline of the element with the subscript-baseline of its parent.

Aligns the baseline of the element with the superscript-baseline of its parent.

Aligns the top of the element with the top of the parent element’s font.

Aligns the bottom of the element with the bottom of the parent element’s font.

Aligns the middle of the element with the baseline plus half the x-height of the parent.

Aligns the baseline of the element to the given length above the baseline of its parent. A negative value is allowed.

Aligns the baseline of the element to the given percentage above the baseline of its parent, with the value being a percentage of the line-height property. A negative value is allowed.

Line-relative values

The following values vertically align the element relative to the entire line:

Aligns the top of the element and its descendants with the top of the entire line.

Aligns the bottom of the element and its descendants with the bottom of the entire line.

For elements that do not have a baseline, the bottom margin edge is used instead.

Values for table cells

baseline (and sub , super , text-top , text-bottom , , and )

Aligns the baseline of the cell with the baseline of all other cells in the row that are baseline-aligned.

Aligns the top padding edge of the cell with the top of the row.

Centers the padding box of the cell within the row.

Aligns the bottom padding edge of the cell with the bottom of the row.

Negative values are allowed.

Formal definition

Initial value baseline
Applies to inline-level and table-cell elements. It also applies to ::first-letter and ::first-line .
Inherited no
Percentages refer to the line-height of the element itself
Computed value for percentage and length values, the absolute length, otherwise the keyword as specified
Animation type a length

Formal syntax

Examples

Basic example

HTML

div> An img src="frame_image.svg" alt="link" width="32" height="32" /> image with a default alignment. div> div> An img class="top" src="frame_image.svg" alt="link" width="32" height="32" /> image with a text-top alignment. div> div> An img class="bottom" src="frame_image.svg" alt="link" width="32" height="32" /> image with a text-bottom alignment. div> div> An img class="middle" src="frame_image.svg" alt="link" width="32" height="32" /> image with a middle alignment. div> 

CSS

img.top  vertical-align: text-top; > img.bottom  vertical-align: text-bottom; > img.middle  vertical-align: middle; > 

Result

Vertical alignment in a line box

HTML

p> top: img style="vertical-align: top" src="star.png" alt="star"/> middle: img style="vertical-align: middle" src="star.png" alt="star"/> bottom: img style="vertical-align: bottom" src="star.png" alt="star"/> super: img style="vertical-align: super" src="star.png" alt="star"/> sub: img style="vertical-align: sub" src="star.png" alt="star"/> p> p> text-top: img style="vertical-align: text-top" src="star.png" alt="star"/> text-bottom: img style="vertical-align: text-bottom" src="star.png" alt="star"/> 0.2em: img style="vertical-align: 0.2em" src="star.png" alt="star"/> -1em: img style="vertical-align: -1em" src="star.png" alt="star"/> 20%: img style="vertical-align: 20%" src="star.png" alt="star"/> -100%: img style="vertical-align: -100%" src="star.png" alt="star"/> p> 
#*  box-sizing: border-box; > img  margin-right: 0.5em; > p  height: 3em; padding: 0 0.5em; font-family: monospace; text-decoration: underline overline; margin-left: auto; margin-right: auto; width: 80%; > 

Result

Vertical alignment in a table cell

HTML

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> There is a theory which states that if ever anyone discovers exactly what the Universe is for and why it is here, it will instantly disappear and be replaced by something even more bizarre and inexplicable. p> p> There is another theory which states that this has already happened. p> td> tr> table> 

CSS

table  margin-left: auto; margin-right: auto; width: 80%; > table, th, td  border: 1px solid black; > td  padding: 0.5em; font-family: monospace; > 

Result

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Jul 18, 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.

Источник

alignment in the cells

The text-align property specifies the horizontal text alignment, and the vertical-align property specifies the vertical alignment.

The text alignment in the cells can be specified by applying these properties to the TD or TH element.

 td < text-align: center; vertical-align: top; >  
Property Value Explanation
text-align
(horizontal)
left aligns to the left
center aligns to the center
right aligns to the right
justify justifies the text
vertical-align
(vertical)
baseline aligns to the baseline
top aligns to the top
middle aligns to the middle
bottom aligns to the bottom

The justify value adjust the spaces between the words to justify both left and right side. (However, the last line is not justified.)

Example

       
The default id soCi">example1">The left id soCi">example2">The center id soCi">example3">The right
       
The default id soCi">example4">The top id soCi">example5">The middle id soCi">example6">The bottom
       
This is example text . id soCi">example7">This is example text .

Output

This is example text. The text-align property specifies the horizontal text alignment. The justify value adjust the spaces between the words to justify both left and right side. This is example text. The text-align property specifies the horizontal text alignment. The justify value adjust the spaces between the words to justify both left and right side.

Aligned to the baseline (Comparison with the «top» value)

      id soCi">example8"> 
abcdefg hijklmn opqrstu vwxyz
abcdefg hijklmn opqrstu vwxyz

Источник

Оцените статью