- CSS Text Alignment
- Text Alignment
- Example
- Example
- Text Align Last
- Example
- Text Direction
- Example
- Vertical Alignment
- Example
- The CSS Text Alignment/Direction Properties
- text-align¶
- Демо¶
- Синтаксис¶
- Значения¶
- Спецификации¶
- Поддержка браузерами¶
- Описание и примеры¶
- CSS text-align
- Syntax
- Possible Values
- New Values in CSS3
- General Information
- Example Code
- Official Specifications
- text-align
- Try it
- Syntax
- Values
- Accessibility concerns
- Formal definition
- Formal syntax
- Examples
- Start alignment
- HTML
- CSS
CSS Text Alignment
In this chapter you will learn about the following properties:
- text-align
- text-align-last
- direction
- unicode-bidi
- vertical-align
Text Alignment
The text-align property is used to set the horizontal alignment of a text.
A text can be left or right aligned, centered, or justified.
The following example shows center aligned, and left and right aligned text (left alignment is default if text direction is left-to-right, and right alignment is default if text direction is right-to-left):
Example
When the text-align property is set to «justify», each line is stretched so that every line has equal width, and the left and right margins are straight (like in magazines and newspapers):
Example
Text Align Last
The text-align-last property specifies how to align the last line of a text.
Example
Align the last line of text in three
elements:
Text Direction
The direction and unicode-bidi properties can be used to change the text direction of an element:
Example
Vertical Alignment
The vertical-align property sets the vertical alignment of an element.
Example
Set the vertical alignment of an image in a text:
img.a <
vertical-align: baseline;
>
img.b vertical-align: text-top;
>
img.c vertical-align: text-bottom;
>
The CSS Text Alignment/Direction Properties
Property | Description |
---|---|
direction | Specifies the text direction/writing direction |
text-align | Specifies the horizontal alignment of text |
text-align-last | Specifies how to align the last line of a text |
unicode-bidi | Used together with the direction property to set or return whether the text should be overridden to support multiple languages in the same document |
vertical-align | Sets the vertical alignment of an element |
text-align¶
Свойство text-align задает горизонтальное выравнивание содержимого встроенного уровня внутри блочного элемента или поля ячейки таблицы.
Это означает, что он работает как vertical-align , но в горизонтальном направлении.
Демо¶
- letter-spacing
- text-decoration
- text-decoration-color
- text-decoration-line
- text-decoration-style
- text-decoration-thickness
- text-decoration-skip
- text-decoration-skip-ink
- text-emphasis
- text-emphasis-color
- text-emphasis-position
- text-emphasis-style
- text-indent
- text-rendering
- text-shadow
- text-underline-position
- text-transform
- white-space
- word-spacing
Синтаксис¶
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/* Keyword values */ 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; /* 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: revert; text-align: revert-layer; text-align: unset;
Значения¶
center Выравнивание текста по центру. Текст помещается по центру горизонтали окна браузера или контейнера, где расположен текстовый блок. Строки текста словно нанизываются на невидимую ось, которая проходит по центру веб-страницы. Подобный способ выравнивания активно используется в заголовках и различных подписях, вроде подрисуночных, он придает официальный и солидный вид оформлению текста. Во всех других случаях выравнивание по центру применяется редко по той причине, что читать большой объем такого текста неудобно. justify Выравнивание по ширине, что означает одновременное выравнивание по левому и правому краю. Чтобы произвести это действие браузер в этом случае добавляет пробелы между словами. left Выравнивание текста по левому краю. В этом случае строки текста выравнивается по левому краю, а правый край располагается «лесенкой». Такой способ выравнивания является наиболее популярным на сайтах, поскольку позволяет пользователю легко отыскивать взглядом новую строку и комфортно читать большой текст. right Выравнивание текста по правому краю. Этот способ выравнивания выступает в роли антагониста предыдущему типу. А именно, строки текста равняются по правому краю, а левый остается «рваным». Из-за того, что левый край не выровнен, а именно с него начинается чтение новых строк, такой текст читать труднее, чем, если бы он был выровнен по левому краю. Поэтому выравнивание по правому краю применяется обычно для коротких заголовков объемом не более трех строк. Мы не рассматриваем специфичные сайты, где текст приходится читать справа налево, там возможно подобный способ выравнивания и пригодится. start Аналогично значению left , если текст идёт слева направо и right , когда текст идёт справа налево. end Аналогично значению right , если текст идёт слева направо и left , когда текст идёт справа налево.
Значение по-умолчанию: left
Применяется к блочным контейнерам
Спецификации¶
Поддержка браузерами¶
Описание и примеры¶
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
html> head> meta charset="utf-8" /> title>text-aligntitle> style> div border: 1px solid black; /* Параметры рамки */ padding: 5px; /* Поля вокруг текста */ margin-bottom: 5px; /* Отступ снизу */ > #left text-align: left; > #right text-align: right; > #center text-align: center; > .content width: 75%; /* Ширина слоя */ background: #fc0; /* Цвет фона */ > style> head> body> div id="left"> div class="content">Выравнивание по левому краюdiv> div> div id="center"> div class="content">Выравнивание по центруdiv> div> div id="right"> div class="content"> Выравнивание по правому краю div> div> body> html>
CSS text-align
The CSS text-align property is used for aligning elements left, right, center etc.
The text-align property has a lot of history within the CSS specifications. Its definition has changed a lot since its introduction in the first CSS specification document in 1996.
In its most recent definition (as of August 2020), the text-align property is defined as a shorthand property that «sets the text-align-all and text-align-last properties and describes how the inline-level content of a block is aligned along the inline axis if the content does not completely fill the line box. Values other than justify-all or match-parent are assigned to text-align-all and reset text-align-last to auto .»
Although the property name is text-align , it applies to all inline content of a block container. Therefore, it’s not just limited to aligning text — it’s for aligning any inline-level content within a block level element (as long as it doesn’t completely fill the block container).
It’s important to note that any alignment specified with text-align is not with respect to the viewport or containing block. A block of text is a stack of line boxes. The text-align property specifies how the inline-level boxes within each line box align with respect to the start and end sides of the line box.
Syntax
Possible Values
Specifies that inline-level content is aligned to the start edge of the line box. Specifies that inline-level content is aligned to the end edge of the line box. Specifies that inline-level content is aligned to the line left edge of the line box. (In vertical writing modes, this will be either the physical top or bottom, depending on the value of the text-orientation property.) Specifies that inline-level content is aligned to the line right edge of the line box. (In vertical writing modes, this will be either the physical top or bottom, depending on the value of the text-orientation property.) Specifies that inline-level content is centered within the line box. Specifies that text is justified according to the method specified by the text-justify property, in order to exactly fill the line box. This value behaves the same as inherit (computes to its parent’s computed value) except that an inherited start or end keyword is interpreted against its parent’s direction value and results in a computed value of either left or right . Sets both text-align-all and text-align-last to justify, forcing the last line to justify as well.
New Values in CSS3
The CSS3 specification (specifically, the Text Module Level 3) proposed four new values: start , end , start , match-parent , and start-end .
The specification has since dropped the start-end and introduced justify-all .
As of this writing, the specification is still only at Working Draft status, so these values may or may not be included in the final recommendation.
In addition, all CSS properties also accept the following CSS-wide keyword values as the sole component of their property value:
initial Represents the value specified as the property’s initial value. inherit Represents the computed value of the property on the element’s parent. unset This value acts as either inherit or initial , depending on whether the property is inherited or not. In other words, it sets all properties to their parent value if they are inheritable or to their initial value if not inheritable.
General Information
CSS2: A nameless value that acts as left if direction is ltr , right if direction is rtl .
Applies To Block containers Inherited? Yes Animatable Discrete (see example)
Example Code
Official Specifications
- CSS Text Module Level 3 (W3C Working Draft, 29 April 2020)
- CSS Text Module Level 3 (W3C Last Call Working Draft 10 October 2013)
- CSS Level 2.1 (W3C Recommendation 07 June 2011)
- CSS Level 1 (W3C Recommendation 17 Dec 1996)
text-align
The text-align CSS property sets the horizontal alignment of the inline-level content inside a block element or table-cell box. This means it works like vertical-align but in the horizontal direction.
Try it
Syntax
/* Keyword values */ 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; /* 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: revert; text-align: revert-layer; 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
The same as left if direction is left-to-right and right if direction is right-to-left.
The same as right if direction is left-to-right and left if direction is right-to-left.
The inline contents are aligned to the left edge of the line box.
The inline contents are aligned to the right edge of the line box.
The inline contents are centered within the line box.
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.
Same as justify , but also forces the last line to be justified.
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
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; >