vertical-align

Свойство CSS vertical-align

Свойство CSS vertical-align отвечает за вертикальное выравнивание текста, картинок на странице. Важной особенностью является то, что он работает только с элементами таблицы, inline и inline-block элементами. Поддерживается всеми современными браузерами.

Синтаксис CSS vertical-align

Где value может принимать следующие значения:

  • baseline — выравнивание по базовой линии предка (или просто нижняя граница родителя)
  • bottom — выравнивание по нижней части строки (или элемента, который располагается ниже всех)
  • middle — выравнивание средней точки элемента по базовой линии родителя плюс половина высоты родительского элемента
  • sub — отображение происходит под строкой (выглядит как подстрочный индекс)
  • super — отображение происходит над строкой (как верхний индекс)
  • text-bottom — выравнивание нижней границы элемента по нижнему краю строки
  • text-top — выравнивание верхняя границы элемента по верхнему краю строки
  • top — выравнивание верхняя края элемента по верху самого высокого элемента строки
  • inherit — наследует значение родителя
  • значение — указывается в пикселях. Положительное число смещает вверх относительно базовой линии. Отрицательное вниз
  • проценты — указывается в процетах. Положительное число смещает вверх относительно базовой линии. Отрицательное вниз
Читайте также:  METANIT.COM

Значение vertical-align по умолчанию:

Вертикальное выравнивание в таблицах

Чаще всего vertical-align используется в ячейках таблиц. В теге используют атрибут valign .

Синтаксис CSS valign для таблиц

td valign value">value"> или tr valign value">value">

Где value может принимать следующие значения:

  • baseline — выравнивание по базовой линии первой текстовой строки
  • bottom — выравнивание по нижнему краю ячейки таблицы
  • middle — выравнивание по середине ячейки
  • top — выравнивание верхнему краю ячейки
table> tr> td valign value">top"> Выравнивание по верху td> tr> tr> td valign value">middle"> Выравнивание по середине td> tr> tr> td valign value">bottom"> Выравнивание по низу td> tr> table>

Преобразуется на странице в следующее:

Выравнивание по верху
Выравнивание по середине
Выравнивание по низу

Примеры с вертикальными выравниваниями

Пример 1. Значения vertical-align: baseline, bottom, top, sub

html> head> style> .vert_align_baseline< display: inline-block; vertical-align: baseline; background: #ccc; > .vert_align_top< display: inline-block; vertical-align: top; background: #ccc; > .vert_align_bottom< display: inline-block; vertical-align: bottom; background: #ccc; > .vert_align_sub< display: inline-block; vertical-align: sub; background: #ccc; > .vert_align_text_top< display: inline-block; vertical-align: top; background: #ccc; > /style> /head> body> br/>span class css">vert_align_baseline">Текст с выравниванием vert_align_baselinespan> br/>span class css">vert_align_bottom">Текст с выравниванием vert_align_bottomspan> br/>span class css">vert_align_top">Текст с выравниванием vert_align_topspan> br/>span class css">vert_align_sub">Текст с выравниванием vert_align_subspan> /body> /html>

Пример 2. Значения vertical-align: абсолютные значения и проценты

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

html> head> style> .vert_align_abs_plus< display: inline-block; vertical-align: 10px; background: #aaa; > .vert_align_abs_minus< display: inline-block; vertical-align: -5px; background: #aaa; > .vert_align_per_plus< display: inline-block; vertical-align: 50%; background: #aaa; > .vert_align_per_minus< display: inline-block; vertical-align: -30%; background: #aaa; > /style> /head> body> br/>span class css">vert_align_abs_plus">Текст с выравниванием на 10 пикселей вверхspan> br/>span class css">vert_align_abs_minus">Текст с выравниванием на 5 пикселей внизspan> br/>span class css">vert_align_per_plus">Текст с выравниванием на 50% вверхspan> br/>span class css">vert_align_per_minus">Текст с выравниванием на 30% внизspan> /body> /html>

Преобразуется на странице в следующее:

Исходная строка. Текст с выравниванием на 10 пикселей вверх
Исходная строка. Текст с выравниванием на 5 пикселей вниз
Исходная строка. Текст с выравниванием на 50% вверх
Исходная строка. Текст с выравниванием на 30% вниз

Значение vertical-align: middle не выравнивает строчный элемент по центру самого большого элемента в строке (что можно было бы ожидать). Вместо этого значение middle выравнивает элемент относительно гипотетичной строчной буквы «X» (также называемой x-высотой).

Для обращения к vertical-align из JavaScript нужно писать следующую конструкцию:

object.style.verticalAlign value">VALUE"

Источник

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.

Источник

vertical-align

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

Синтаксис

vertical-align: baseline|bottom|middle|sub|super|text-bottom|text-top|top|inherit | значение | проценты

Значения

baseline Выравнивает базовую линию текущего элемента по базовой линии родителя. Если родительский элемент не имеет базовой линии, то за нее принимается нижняя граница элемента. bottom Выравнивает основание текущего элемента по нижней части элемента строки, расположенного ниже всех. middle Выравнивание средней точки элемента по базовой линии родителя плюс половина высоты родительского элемента. sub Элемент изображается как подстрочный, в виде нижнего индекса. Размер шрифта при этом не меняется. super Элемент изображается как надстрочный, в виде верхнего индекса. Размер шрифта остается прежним. text-bottom Нижняя граница элемента выравнивается по самому нижнему краю текущей строки. text-top Верхняя граница элемента выравнивается по самому высокому текстовому элементу текущей строки. top Выравнивание верхнего края элемента по верху самого высокого элемента строки. inherit Наследует значение родителя.

В качестве значения также можно использовать проценты, пикселы или другие доступные единицы. Положительное число смещает элемент вверх относительно базовой линии, в то время как отрицательное число опускает его вниз. При использовании процентов, отсчет ведется от значения свойства line-height , при этом 0% аналогично значению baseline .

Для выравнивания по вертикали в ячейках таблицы применяются следующие значения.

baseline Выравнивает базовую линию ячейки с базовой линией первой текстовой строки или другого вложенного элемента. bottom Выравнивает по нижнему краю ячейки. middle Выравнивает по середине ячейки. top Выравнивает содержимое ячейки по ее верхнему краю.

HTML5 CSS2.1 IE Cr Op Sa Fx

       
TEX и LATEX

Результат данного примера показан на рис. 1.

Применение свойства vertical-align

Рис. 1. Применение свойства vertical-align

Объектная модель

[window.]document.getElementById(» elementID «).style.verticalAlign

Браузеры

Internet Explorer до версии 7.0 включительно не поддерживает значение inherit .

Источник

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