- text-align
- Try it
- Syntax
- Values
- Accessibility concerns
- Formal definition
- Formal syntax
- Examples
- Start alignment
- HTML
- CSS
- Result
- Centered text
- HTML
- CSS
- Result
- Пример использования «justify»
- HTML
- CSS
- text-align
- Синтаксис
- Значения
- Объектная модель
- Браузеры
- text-align
- Syntax
- Values
- Accessibility concerns
- Formal definition
- Formal syntax
- Examples
- Left alignment
- HTML
- CSS
- Result
- Centered text
- HTML
- CSS
- Result
- Justify
- HTML
- CSS
- Result
- Notes
- Specifications
- Browser compatibility
text-align
Свойство CSS text-align задает горизонтальное выравнивание содержимого встроенного уровня внутри блочного элемента или поля ячейки таблицы. Это означает, что он работает как vertical-align но в горизонтальном направлении. vertical-align
Try it
Syntax
/ * Значения ключевых слов * / text-align: start; text-align: end; text-align: left; text-align: right; text-align: center; text-align: justify; text-align: justify-all; text-align: match-parent; / * Выравнивание столбца таблицы по символам * / text-align: "."; text-align: "." center; / * Значения выравнивания блока (нестандартный синтаксис) * / text-align: -moz-center; text-align: -webkit-center; / * Глобальные значения * / text-align: inherit; text-align: initial; text-align: revert; text-align: revert-layer; text-align: unset;
Свойство text-align указывается одним из следующих способов:
- Использование значений ключевых слов start , end , left , right , center , justify , justify-all или match-parent .
- Использование только значения , и в этом случае другое значение по умолчанию имеет right .
- Использование как значения ключевого слова, так и значения .
Values
То же, что left если направление слева направо, и right если направление справа налево.
То же, что right если направление слева направо, и left если направление справа налево.
Содержимое строки выровнено по левому краю коробки с линиями.
Содержимое строки выровнено по правому краю коробки с линиями.
Содержимое строки находится в центре поля.
Встроенное содержание является оправданным.Текст должен быть расположен на расстоянии между левым и правым краями строки,за исключением последней строки.
То же самое, что и justify , но также заставляет последнюю строку быть оправданной.
Подобно inherit , но значения start и end рассчитывается в соответствии с родителем direction и заменяются соответствующими left или right значение.
При применении к ячейке таблицы укажите символ выравнивания,по которому будет выровнено содержимое ячейки.
Accessibility concerns
Несоответствие между словами,созданными обоснованным текстом,может быть проблематичным для людей с когнитивными проблемами,такими как дислексия.
Formal definition
Initial value | start или безымянное значение, которое действует как left , если direction равно ltr , right , если direction равно rtl , если start не поддерживается браузером. |
---|---|
Applies to | block containers |
Inherited | yes |
Computed value | как указано, за исключением значения match-parent , которое рассчитывается относительно значения direction его родителя и приводит к вычисленному значению left или right |
Animation type | discrete |
Formal syntax
text-align = start | end | left | right | center | justify | match-parent | justify-all
Examples
Start alignment
HTML
p class="example"> Integer elementum massa at nulla placerat varius. Suspendisse in libero risus, in interdum massa. Vestibulum ac leo vitae metus faucibus gravida ac in neque. Nullam est eros, suscipit sed dictum quis, accumsan a ligula. p>
CSS
.example < text-align: start; border: solid; >
Result
Centered text
HTML
p class="example"> Integer elementum massa at nulla placerat varius. Suspendisse in libero risus, in interdum massa. Vestibulum ac leo vitae metus faucibus gravida ac in neque. Nullam est eros, suscipit sed dictum quis, accumsan a ligula. p>
CSS
.example < text-align: center; border: solid; >
Result
Пример использования «justify»
HTML
p class="example"> Integer elementum massa at nulla placerat varius. Suspendisse in libero risus, in interdum massa. Vestibulum ac leo vitae metus faucibus gravida ac in neque. Nullam est eros, suscipit sed dictum quis, accumsan a ligula. p>
CSS
.example < text-align: justify; border: solid; >
text-align
Определяет горизонтальное выравнивание текста в пределах элемента.
Синтаксис
text-align: center | justify | left | right | inherit
text-align: center | justify | left | right | start | end
Значения
center Выравнивание текста по центру. Текст помещается по центру горизонтали окна браузера или контейнера, где расположен текстовый блок. Строки текста словно нанизываются на невидимую ось, которая проходит по центру веб-страницы. Подобный способ выравнивания активно используется в заголовках и различных подписях, вроде подрисуночных, он придает официальный и солидный вид оформлению текста. Во всех других случаях выравнивание по центру применяется редко по той причине, что читать большой объем такого текста неудобно. justify Выравнивание по ширине, что означает одновременное выравнивание по левому и правому краю. Чтобы произвести это действие браузер в этом случае добавляет пробелы между словами. left Выравнивание текста по левому краю. В этом случае строки текста выравнивается по левому краю, а правый край располагается «лесенкой». Такой способ выравнивания является наиболее популярным на сайтах, поскольку позволяет пользователю легко отыскивать взглядом новую строку и комфортно читать большой текст. right Выравнивание текста по правому краю. Этот способ выравнивания выступает в роли антагониста предыдущему типу. А именно, строки текста равняются по правому краю, а левый остается «рваным». Из-за того, что левый край не выровнен, а именно с него начинается чтение новых строк, такой текст читать труднее, чем, если бы он был выровнен по левому краю. Поэтому выравнивание по правому краю применяется обычно для коротких заголовков объемом не более трех строк. Мы не рассматриваем специфичные сайты, где текст приходится читать справа налево, там возможно подобный способ выравнивания и пригодится. auto Не изменяет положение элемента. inherit Наследует значение родителя. start Аналогично значению left , если текст идёт слева направо и right , когда текст идёт справа налево. end Аналогично значению right , если текст идёт слева направо и left , когда текст идёт справа налево.
HTML5 CSS2.1 IE Cr Op Sa Fx
Результат данного примера показан на рис. 1.
Рис. 1. Выравнивание текста в браузере Safari
Internet Explorer до версии 7.0 включительно несколько иначе трактует данный пример, чем другие браузеры, выравнивая не только текст, но и блоки (рис. 2).
Рис. 2. Выравнивание текста в браузере Internet Explorer 7
Объектная модель
[window.]document.getElementById(» elementID «).style.textAlignБраузеры
IE до версии 7.0 включительно выравнивает не только содержимое блочного элемента, но и сам элемент.
text-align
The text-align CSS property sets the horizontal alignment of a block element or table-cell box. This means it works like vertical-align but in the horizontal direction.
The source for this interactive example is stored in a GitHub repository. If you’d like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
Syntax
/* Keyword values */ text-align: left; text-align: right; text-align: center; text-align: justify; text-align: justify-all; text-align: start; text-align: end; text-align: match-parent; /* Character-based alignment in a table column */ text-align: "."; text-align: "." center; /* Block alignment values (Non-standard syntax) */ text-align: -moz-center; text-align: -webkit-center; /* Global values */ text-align: inherit; text-align: initial; text-align: unset;
The text-align property is specified in one of the following ways:
- Using the keyword values start , end , left , right , center , justify , justify-all , or match-parent .
- Using a value only, in which case the other value defaults to right .
- Using both a keyword value and a value.
Values
start The same as left if direction is left-to-right and right if direction is right-to-left. end The same as right if direction is left-to-right and left if direction is right-to-left. left The inline contents are aligned to the left edge of the line box. right The inline contents are aligned to the right edge of the line box. center The inline contents are centered within the line box. justify The inline contents are justified. Text should be spaced to line up its left and right edges to the left and right edges of the line box, except for the last line. justify-all Same as justify , but also forces the last line to be justified. match-parent Similar to inherit , but the values start and end are calculated according to the parent’s direction and are replaced by the appropriate left or right value. When applied to a table cell, specifies the alignment character around which the cell’s contents will align.
Accessibility concerns
The inconsistent spacing between words created by justified text can be problematic for people with cognitive concerns such as Dyslexia.
Formal definition
Initial value | start , or a nameless value that acts as left if direction is ltr , right if direction is rtl if start is not supported by the browser. |
---|---|
Applies to | block containers |
Inherited | yes |
Computed value | as specified, except for the match-parent value which is calculated against its parent’s direction value and results in a computed value of either left or right |
Animation type | discrete |
Formal syntax
start | end | left | right | center | justify | match-parent
Examples
Left alignment
HTML
Integer elementum massa at nulla placerat varius. Suspendisse in libero risus, in interdum massa. Vestibulum ac leo vitae metus faucibus gravida ac in neque. Nullam est eros, suscipit sed dictum quis, accumsan a ligula.
CSS
Result
Centered text
HTML
Integer elementum massa at nulla placerat varius. Suspendisse in libero risus, in interdum massa. Vestibulum ac leo vitae metus faucibus gravida ac in neque. Nullam est eros, suscipit sed dictum quis, accumsan a ligula.
CSS
Result
Justify
HTML
Integer elementum massa at nulla placerat varius. Suspendisse in libero risus, in interdum massa. Vestibulum ac leo vitae metus faucibus gravida ac in neque. Nullam est eros, suscipit sed dictum quis, accumsan a ligula.
CSS
Result
Notes
The standard-compatible way to center a block itself without centering its inline content is setting the left and right margin to auto , e.g.:
Specifications
Specification | Status | Comment |
---|---|---|
CSS Logical Properties and Values Level 1 The definition of ‘text-align’ in that specification. | Editor’s Draft | No changes |
CSS Text Module Level 4 The definition of ‘text-align’ in that specification. | Editor’s Draft | Added the value. |
CSS Text Module Level 3 The definition of ‘text-align’ in that specification. | Working Draft | Added the start , end , and match-parent values. Changed the unnamed initial value to start (which it was). |
CSS Level 2 (Revision 1) The definition of ‘text-align’ in that specification. | Recommendation | No changes |
CSS Level 1 The definition of ‘text-align’ in that specification. | Recommendation | Initial definition |
Browser compatibility
The compatibility table in this page is generated from structured data. If you’d like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.
Desktop | Mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | Android webview | Chrome for Android | Firefox for Android | Opera for Android | Safari on iOS | Samsung Internet | |
text-align | Chrome Full support 1 | Edge Full support 12 | Firefox Full support 1 | IE Full support 3 | Opera Full support 3.5 | Safari Full support 1 | WebView Android Full support ≤37 | Chrome Android Full support 18 | Firefox Android Full support 4 | Opera Android Full support 10.1 | Safari iOS Full support 1 | Samsung Internet Android Full support 1.0 |
Prefixed center , left , and right values for block alignment |