What values ​​can the text align property take? CSS properties for styling HTML text (vertical-align, text-align, text-indent and others). HTML tags that determine text alignment and indentation

💖 Do you like it? Share the link with your friends

The CSS text-align property is responsible for horizontally aligning text, as well as images and other elements. The property has 4 possible options alignment.

CSS text-align syntax

...text-align: center | justify | left | right | inherit; ...
  • center - alignment to the center of the area (for example, the width of the area is 500 pixels, which means the alignment will be along a line of 250 pixels)
  • justify - stretches text across the entire width of the area
  • left - left alignment
  • right - right alignment
  • inherit - accept the value of the ancestor (parent)

Most often these properties are used in blocks

and paragraphs

Note:
There is also a vertical-align property, which controls the vertical alignment.

How to do text alignment in html

Example No. 1.

Align text to the left. Valid by default.

Выравнивание текста по левому краю

Выравнивание текста по левому краю

Пример №2. Выравнивание текста и картинки по центру

Выравнивание текста по центру. Зачастую используются для заглавия статей или для вывода картинок по центру.

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

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

Выравнивание текста по левому краю

Пример №3. Выравнивание текста по правому краю

Выравнивание текста по правому краю.

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

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

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

Пример №4. Выравнивание текста по ширине всей области

Выравнивание текста по всей ширине. Получается, что выравнивание происходит и полевому, и по правому краю. Браузер автоматически добавляет пробелы.

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

Выравнивание текста по ширине всей области

Иногда text-align: justify; может не работать. Это связано с наследованием и даже с работой браузера. В целом не рекомендуется использовать этот параметр.

Примечание

Вместо свойства text-align можно также использовать атрибут align , который пишется вместе с тегом. Его можно использовать у различных тегов. Например:

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

Выравнивание текста по ширине всей области

... ...

Разница в тегах

и

В том, что последний делает переход на новую строку (вертикальный отступ), а div не делает.

HTML теги, определяющие выравнивание текста, отступ

Выровненный по ширине текст используется в типографии

В примере ниже показано, как выровнить текст по ширине страницы:

align="left" align="right"

С каждым днем растет число работников занятых в сфере услуг и распространении информации. Если символами прошлых столетий были ферма и фабрика, то символ нынешнего XXI века – это офис, оборудованный компьютерами, которые имеют доступ к информационному потоку.

align="justify" align="center"

С каждым днем растет число работников занятых в сфере услуг и распространении информации. Если символами прошлых столетий были ферма и фабрика, то символ нынешнего XXI века – это офис, оборудованный компьютерами, которые имеют доступ к информационному потоку.

С каждым днем растет число работников занятых в сфере услуг и распространении информации. Если символами прошлых столетий были ферма и фабрика, то символ нынешнего XXI века – это офис, оборудованный компьютерами, которые имеют доступ к информационному потоку.

Значение justify обеспечивает равномерное выравнивание текста справа и слева , то есть по ширине . Такой метод широко используется в печати.

Выравнивание текста в HTML по центру и по ширине

Выравнивание текста в HTML по центру, текст справа :

Результат:

Атрибуты и значения

  • align="left" - определяет выравнивание текста слева (по умолчанию).
  • align="center" - выравнивает текст по центру .
  • align="right" - выравнивает текст справа .

Выравнивание | HTML отступ текста

HTML текст и его отступ слева страницы

Произведем отступ текста слева двумя способами:

Результат:

Посмотреть в новом окне.

CSS Internet Explorer Chrome Opera Safari Firefox Android iOS
2.1 6.0+ 8.0+ 1.0+ 3.5+ 1.0+ 1.0+ 1.0+ 1.0+
3 2.0+ 11.6+ 3.1+ 3.6+ 2.1+ 2.0+

Краткая информация

Версии CSS

Значения

center Выравнивание текста по центру. Текст помещается по центру горизонтали окна браузера или контейнера, где расположен текстовый блок. Строки текста словно нанизываются на невидимую ось, которая проходит по центру веб-страницы. Подобный способ выравнивания активно используется в заголовках и различных подписях, вроде подрисуночных, он придает официальный и солидный вид оформлению текста. Во всех других случаях выравнивание по центру применяется редко по той причине, что читать большой объем такого текста неудобно. justify Выравнивание по ширине, что означает одновременное выравнивание по левому и правому краю. Чтобы произвести это действие браузер в этом случае добавляет пробелы между словами. left Выравнивание текста по левому краю. В этом случае строки текста выравнивается по левому краю, а правый край располагается «лесенкой». Такой способ выравнивания является наиболее популярным на сайтах, поскольку позволяет пользователю легко отыскивать взглядом новую строку и комфортно читать большой текст. right Выравнивание текста по правому краю. Этот способ выравнивания выступает в роли антагониста предыдущему типу. А именно, строки текста равняются по правому краю, а левый остается «рваным». Из-за того, что левый край не выровнен, а именно с него начинается чтение новых строк, такой текст читать труднее, чем, если бы он был выровнен по левому краю. Поэтому выравнивание по правому краю применяется обычно для коротких заголовков объемом не более трех строк. Мы не рассматриваем специфичные сайты, где текст приходится читать справа налево, там возможно подобный способ выравнивания и пригодится. auto Не изменяет положение элемента. inherit Наследует значение родителя. start Аналогично значению left , если текст идёт слева направо и right , когда текст идёт справа налево. end Аналогично значению right , если текст идёт слева направо и left , когда текст идёт справа налево.

HTML5 CSS2.1 IE Cr Op Sa Fx

text-align

Left alignment
Center alignment


The result of this example is shown in Fig. 1.

Rice. 1. Align text in Safari browser

Internet Explorer up to and including version 7.0 interprets this example somewhat differently than other browsers, aligning not only text, but also blocks (Fig. 2).

Rice. 2. Align text in Internet browser Explorer 7

Object Model

document.getElementById("elementID ").style.textAlign

Browsers

IE up to and including version 7.0 aligns not only the contents of a block-level element, but also the element itself.

Property text-align-last ( not to be confused with HTML align) determines how the last line of a block or the line before a forced break will be aligned. This is important because in last line a paragraph usually does not contain enough text to fill all the space.

In this article, we'll cover all aspects of the text-align-last property, including the values ​​it accepts and browser support.

Usage and accepted values

Using the text-align-last property is simple. Here's a code snippet to align the last line of text to the right:

Intro-graph ( text-align: justify; // Required for IE and Edge text-align-last: right; )

The property can take seven values. You're probably familiar with the standard HTML text values ​​of align:left , right , and center . They align the text on the last line to the right, left, and center of the container.

The example below illustrates the differences between these three values:

View example

The fourth value, justify , justifies the last line so that the text is evenly distributed across the entire width of the container. This is achieved by adding an appropriate number of spaces between words. Depending on the amount of text, this property can be used to completely fill the space in the last line without ending up with too large gaps between words.

The text in the second paragraph is also spread across the width, but since the last line contains only one word, it is positioned to the left.

View example

Aligning the last line of text to the left is suitable for languages ​​that are read from left to right ( LTR), but this will be incorrect for RTL languages. In such cases, using the left or right values ​​can cause problems.

Fortunately, you can use the start value to align text to the edge where writing and reading begin. This means that by setting the text-align-last property to start , you will align text left for LTR languages ​​and right aligned for RTL languages.

You can also use the end value to align text on the opposite edge from where you start writing and reading. This will correspond to the value right for LTR languages ​​and left for RTL languages.

View example

The default value for this property is auto . When used, the text in the last line is aligned according to the value HTML properties text align unless it is set to justify . Otherwise, text is distributed across the width of the container only if the text-justify property is set to distribute . Otherwise, the text is aligned to the edge where writing and reading begin.

Important Notes

For text-align-last to work, the text-align property must be set to justify . But this rule is only implemented in IE and Edge. In Firefox and Chrome, the property works without setting text-align to justify . In the example below, the text should be right aligned in Edge and IE. In other browsers, the last lines of paragraphs will be aligned according to the value of the text-align-last property, and the remaining lines will be right-aligned.

View demo

If we don't set text-align to align justify HTML , the result doesn't look as nice. Therefore, you will most likely set the text distribution to width.

The property works even if the paragraph has a forced line break specified using the tag
or something like that. Keep in mind that this property will affect all last lines of text within the specified element, not just the outermost one. For example, if the text inside an article or div element contains three paragraphs, the last line in each will be aligned according to the text-align-last property set for the entire parent element.

If you only need to align the very last line of content, you can use the :last-child or :last-of-type selectors. Take the code from the demo below as an example:

article ( text-align: justify; ) article p:last-of-type ( text-align-last: right; )

It aligns the last line of the last paragraph of our article to the right. The remaining lines are aligned based on the value of the HTML text align property.

View demo

You can also use other selectors: :even and :odd to change the alignment.

Sometimes a paragraph may only consist of one line. In this case, if you specified values ​​for both the text-align property and the text-align-last property, then the latter property will take precedence.

Consider the following code snippet:

p ( text-align: justify; ) p:nth-of-type(2) ( text-align-last: left; )

If the second paragraph has only one line, then the text will be left aligned because text-align-last will take precedence. The demo below shows this CSS code in action, as well as a few others. HTML examples align.

View demo

Browser support

Support for this property can be enabled using the option " Enable experimental web platform features" V Google Chrome and Opera, starting with versions 35 and 22 respectively. It is fully supported in Chrome 47+ and Opera 34+.

To use this property in Firefox, you will have to prefix it with -moz- . The start and end values ​​are not supported by IE. At the same time, Edge fully supports this property. The only popular browser that does not fully support text-align-last is Safari.

Sets the alignment of the last line of a block of text.

brief information

Designations

DescriptionExample
<тип> Indicates the type of the value.<размер>
A && BThe values ​​must be output in the order specified.<размер> && <цвет>
A | BIndicates that you need to select only one value from the proposed ones (A or B).normal | small-caps
A || BEach value can be used independently or together with others in any order.width || count
Groups values.[ crop || cross ]
* Repeat zero or more times.[,<время>]*
+ Repeat one or more times.<число>+
? The specified type, word, or group is optional.inset?
(A, B)Repeat at least A, but no more than B times.<радиус>{1,4}
# Repeat one or more times separated by commas.<время>#
×

Values

auto Matches the alignment specified by the text-align property, except for the justify value. For it, the alignment will be like start . start The line is aligned to the starting edge of the block, which can change depending on the direction of the text (left to right or right to left). end The line is aligned to the ending edge of the block, which is determined by the direction of the text. left The line is aligned to the left. right The line is aligned to the right. center The line is centered. justify The line is justified. If there is only one word in the last line, it will be left aligned.

Influence different meanings The position of the text is shown in table. 1.

Table 1. Impact of text-align-last values
MeaningAlignmentText type
leftLeft
rightRight
centerCentered
justifyWidth

Sandbox

Winnie the Pooh was always not averse to a little refreshment, especially at eleven in the morning, because at that time breakfast had long ended, and lunch had not yet begun. And, of course, he was terribly happy to see that the Rabbit was taking out cups and plates.

div ( text-align-last: start ; )

Example

text-align-last

When crossing mountains, lean on the valley; position yourself at heights, depending on where the sunny side is. When fighting an enemy on high ground, do not go straight up. This is the disposition of the army in the mountains.


Object Model

An object.style.textAlignLast

Note

Internet Explorer and Edge do not support start and end values.

Firefox before version 49 supports the -moz-text-align-last property.

Specification

Each specification goes through several stages of approval.

  • Recommendation - The specification has been approved by the W3C and is recommended as a standard.
  • Candidate Recommendation ( Possible recommendation) - the group responsible for the standard is satisfied that it meets its goals, but requires help from the development community to implement the standard.
  • Proposed Recommendation Suggested Recommendation) - at this stage the document is submitted to the W3C Advisory Council for final approval.
  • Working Draft - A more mature version of a draft that has been discussed and amended for community review.
  • Editor's draft ( Editorial draft) - a draft version of the standard after changes were made by the project editors.
  • Draft ( Draft specification) - the first draft version of the standard.
×

tell friends