- text-align
- Try it
- Syntax
- Values
- Accessibility concerns
- Formal definition
- Formal syntax
- Examples
- Start alignment
- HTML
- CSS
- Выравнивание текста
- How to center text in HTML
- Using the tags
- Using a style sheet property
- Centering a few blocks of text
- Multiple blocks of text
- Examples of centered text and objects
- Centering text in a paragraph
- Centering an image
- Centering a URL hyperlink
- Centering text in a header tag Example of centered text in a header tag Example of centered text in a header tag Centering text in a tag Example of a centered sentence in a div tag. Example of a second centered sentence in a div tag.
Выравнивание текста
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; >
Выравнивание текста
Выравнивание текста определяет его внешний вид и ориентацию краев абзаца и может выполняться по левому краю, правому краю, по центру или по ширине. В табл. 1 показаны варианты выравнивания блока текста.
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diem nonummy nibh euismod tincidunt ut lacreet dolore magna aliguam erat volutpat.
Наиболее распространенный вариант — выравнивание по левому краю, когда слева текст сдвигается до края, а правый остается неровным. Выравнивание по правому краю и по центру в основном используется в заголовках и подзаголовках. Следует иметь в виду, что при использовании выравнивания по ширине в тексте между словами могут появиться большие интервалы, что не очень красиво.
Для установки выравнивания текста обычно используется тег абзаца
с атрибутом align , который определяет способ выравнивания. Также блок текста допустимо выравнивать с помощью тега с аналогичным атрибутом align , как показано в табл. 2.
Код HTML | Описание |
---|---|
Текст | Добавляет новый абзац текста, по умолчанию выровненный по левому краю. Перед абзацем и после него автоматически добавляются небольшие вертикальные отступы. |
Текст | Выравнивание по центру. |
Текст | Выравнивание по левому краю. |
Текст | Выравнивание по правому краю. |
Текст | Выравнивание по ширине. |
Отключает автоматический перенос строк, даже если текст шире окна браузера. | |
Текст | Разрешает браузеру делать перенос строки в указанном месте, даже если используется тег |
Текст | Выравнивание по центру. |
Текст | Выравнивание по левому краю. |
Текст | Выравнивание по правому краю. |
Текст | Выравнивание по ширине. |
Выравнивание элементов по левому краю задано по умолчанию, поэтому указывать его лишний раз необходимости нет. Так что align=»left» можно опустить.
Отличие между абзацем (тег
) и тегом в том, что в начале и конце параграфа появляется вертикальный отступ, чего нет в случае использования тега .
Атрибут align достаточно универсален и может применяться не только к основному тексту, но и к заголовкам вроде . В примере 1 показано, как в подобном случае устанавливать выравнивание.
Пример 1. Выравнивание текста
Как поймать льва?
Метод перебора
Делим пустыню на ряд элементарных участков, размер которых совпадает с габаритными размерами льва, но при этом меньше размера клетки. Далее простым перебором определяем участок, в котором находится лев, что автоматически приводит к его поимке.
Метод дихотомии
Делим пустыню на две половины. В одной части - лев, в другой его нет. Берем ту половину, в которой находится лев, и снова делим ее пополам. Так повторяем до тех пор, пока лев не окажется пойман.
Результат примера показан на рис. 1.
Рис. 1. Выравнивание текста по правому и левому краю
В данном примере выравнивание заголовка происходит по центру окна браузера, выделенного абзаца по правому краю, а основного текста — по левому краю.
How to center text in HTML
Centering text is generally used for a title of a website or document. To center text using HTML (hypertext markup language), you can use the tag or use a CSS (cascading style sheets) property. To proceed, select the option you prefer and follow the instructions.
Using the tags
One way to center text or put it in the middle of the page is to enclose it in tags.
Using the example HTML code above yields the following result:
The tag is now considered deprecated. Although it may still work, it’s expected to be removed in favor of using CSS. We recommend you use the style sheet method (shown below) to center text in HTML.
Using a style sheet property
You can center text on a website with CSS by specifying the text-align property of the element to be centered.
Centering a few blocks of text
If you only have one or a few blocks of text to center, add the style attribute to the element’s opening tag and use the «text-align» property. In the example below, we added the attribute and property to the tag.
The «text-align» property is set to «center» to indicate the element is centered in the middle of the page or containing div.
Multiple blocks of text
If you have many blocks of text to center, use CSS inside tags in the head or in an external style sheet. See the example code below for how to set all text in the tags to be centered.
The text in every set of tags is centered on the page. If you want some paragraphs centered, while others are not, you can create a style class, as seen in the code below.
If you’re creating a center class, as shown in the example above, a paragraph can be centered using the code below, which «calls» the center class.
Once a class is created, it can be applied to any HTML tag containing words, images, and most other objects. For example, if you want a heading to be centered, you could add class=»center» to the tag or another heading tag.
Examples of centered text and objects
Below are examples of using the style attribute and «text-align» property to center text and objects on a web page.
Centering text in a paragraph
Example of centered text in a paragraph.
Example of centered text in a paragraph.
Centering an image
Centering a URL hyperlink
Centering text in a header tag
Example of centered text in a header tag
Example of centered text in a header tag
Centering text in a tag
Example of a centered sentence in a div tag.
Example of a second centered sentence in a div tag.
Example of centered sentence in a div tag.
Example of a second centered sentence in a div tag.