The text-align CSS property is responsible for the horizontal alignment of 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, so it will be aligned to the 250 pixels line)
- justify - stretches the text across the entire width of the region
- left - left alignment
- right - right alignment
- inherit - take the value of the ancestor (parent)
These properties are most commonly used in blocks.
Note:
There is also a vertical-align property, which is responsible for vertical alignment.
How to align text in html
Example # 1.
Aligns the text to the left. Valid by default.
Выравнивание текста по левому краю
Выравнивание текста по левому краю
Пример №2. Выравнивание текста и картинки по центру
Выравнивание текста по центру. Зачастую используются для заглавия статей или для вывода картинок по центру.
Выравнивание текста по центру
На странице преобразуется в следующее
Выравнивание текста по левому краю
Пример №3. Выравнивание текста по правому краю
Выравнивание текста по правому краю.
Выравнивание текста по правому краю
На странице преобразуется в следующее
Выравнивание текста по правому краю
Пример №4. Выравнивание текста по ширине всей области
Выравнивание текста по всей ширине. Получается, что выравнивание происходит и полевому, и по правому краю. Браузер автоматически добавляет пробелы.
На странице преобразуется в следующее
Выравнивание текста по ширине всей области
Иногда text-align: justify; может не работать. Это связано с наследованием и даже с работой браузера. В целом не рекомендуется использовать этот параметр.
ПримечаниеВместо свойства text-align можно также использовать атрибут align , который пишется вместе с тегом. Его можно использовать у различных тегов. Например:
Выравнивание по центруВыравнивание текста по ширине всей области
... ...
Разница в тегах
В том, что последний делает переход на новую строку (вертикальный отступ), а div не делает.
Здравствуйте, уважаемые читатели блога сайт. В этой статье мы продолжаем изучать основы стилевой разметки CSS и рассмотрим свойства vertical-align, text-align, text-indent и некоторые другие, предназначенные для оформления текста html.
Выравнивание текста с помощью CSS
Начнем с атрибутов стиля, управляющих выводом текста в блочных элементах. Начнем со свойства text-align, которое является фактически заменой атрибута align (используется для выравнивания содержимого html-элементов, например абзацев p).
Свойство стиля text-align задает горизонтальное выравнивание текста и имеет всего четыре возможных значения:
Доступные значения этого правила определяют выравнивание, соответственно: left — по левому краю, right — по правому краю, center — по центру и justify — по ширине страницы (одновременно по левому и правому краю за счет увеличения расстояния между словами). Для примера, текст этой статьи выравнен по ширине страницы (если вы заметили у него ровные границы и слева и справа) с помощью правила text-align:justify.
По умолчанию, горизонтальное выравнивание выполняется по левому краю, поэтому специально указывать text-align:left не обязательно, если в родительских элементах не было указано другого выравнивания.
Примеры использования свойства:
Следующее свойство CSS text-ident задает отступ для красной строки , например для текста в теге абзаца p. Это правило также, как и text-align, применимо только для блочных элементов. Синтаксис:
Здесь допускаются абсолютные и относительные величины отступа. Абсолютные значения (px — пикселы, em, ex и др.) можно указывать как со знаком плюс, так и со знаком минус. Относительная величина обычно задается в процентах (%). Относительное значение рассчитывается от ширины области, которая отведена под текст. Так, css правило text-indent:50% задаст красную строку равную половине длины этой самой строки. По умолчанию отступ «красной строки» равен нулю. Пример:
Далее рассмотрим вертикальное выравнивание — свойство vertical-align . Это свойство применимо уже для всех html элементов и практически для всех означает выравнивание между собой строчных элементов с текстом относительно их базовой линии. Кроме тегов таблицы td и th, в которых по вертикали будет выравниваться весь контент. Синтаксис:
Рассмотрим каждое значение подробнее:
- baseline — выравнивание фрагмента текста по базовой линии родительского элемента. Это значение по умолчанию;
- sub — фрагмент текста изображается в виде нижнего индекса или подстрочным для родительского элемента;
- super — фрагмент текста изображается в виде верхнего индекса или надстрочным для родительского элемента;
- top — выравнивание фрагмента текста по верхнему краю родительского элемента;
- text-top — выравнивание фрагмента по верхнему краю текста родительского элемента;
- middle — выравнивание центра фрагмента текста по центру родительского элемента;
- bottom — выравнивание фрагмента текста по нижнему краю родительского элемента;
- text-bottom — выравнивание фрагмента по нижнему краю текста родительского элемента;
На рисунке ниже можно посмотреть поведение фрагментов теста при различных значениях свойства vertical-align в браузере Internet Explorer 11:
Кроме вышеперечисленных значений, можно указывать числовые значения. Так, правило CSS vertical-align:0 будет означать тоже самое, что и запись vertical-align:baseline. А правило vertical-align:10px будет смещать текст вверх на 10 пикселей относительно базовой линии. Для смещения текста вниз значение необходимо указывать с минусом.
Сдвиг также можно задавать в относительных единицах измерения, например в em и в ex или в процентах.
Для вертикального выравнивания содержимого ячеек таблицы в vertical-align следует использовать значения:
- top — для выравнивания содержимого по верхней границе ячейки;
- bottom — для выравнивания содержимого по нижней границе ячейки;
- middle — для выравнивания по центру ячейки (используется по умолчанию).
Для достижения нужного результата, обычно приходится экспериментировать с различными значениями свойства стиля vertical-align. Многочисленные возможные значения дают слишком разный результат в различных случаях.
Параметры white-space и word-wrap, управляющие разрывом строк
На очереди параметр white-space, который отвечает за отображение пробельных символов на html странице.
Как мы знаем, по умолчанию браузер объединяет все подряд идущие пробельные символы: пробелы, переносы строк и символы табуляции, — в один пробел. Исключение тег «pre» , помещенный в него текст отображается как есть, со всеми пробелами.
Свойство white-space имеет следующий синтаксис:
Понятно, что значение normal используется по умолчанию и оставляет все как описывалось выше, все подряд идущие пробелы объединяются в один и перенос строк устанавливается автоматически.
Использование значения «pre», будет полной аналогией при применении тега «pre». Браузер будет отображать страницу с учетом всех лишних пробелов и переносов, как они были добавлены разработчиком. Если строка текста получиться слишком длинной, то будет добавлена горизонтальная полоса прокрутки.
Значение nowrap запрещает браузеру переносить строки и текст отображается одной строкой. Единственное, добавление тега «br» позволит перенести текст на новую строку.
Значение pre-wrap сохраняет все последовательности пробелов и переносов строк, но если строка не помещается в заданную область, то браузер автоматически переносит текст на новую строку.
Ну и значение pre-line преобразует пробелы в один пробел, переводы строк сохраняются и браузер может разорвать слишком длинные строки, чтобы избежать горизонтальной прокрутки.
Пример использования:
Далее рассмотрим параметр word-wrap , который поваляет указать переносить или нет длинные слова, которые не помещаются в заданную область. Это свойство применяется не часто, но иногда без него не обойтись:
word-wrap: normal|break-word
Значение normal указывает браузеру, что текст можно разрывать только по пробелам и это обычное поведение браузера. А значение break-word разрешает браузеру вставлять разрывы строк внутри слов. Пример:
Параметры тени у текста — свойство text-shadow
Для любителей различных украшательств в стандарте CSS3 появилась возможность задавать тень у текста. Грамотное использования свойства text-shadow позволяет заметно оживить web страницу. Синтаксис:
Значение none отменяет добавление тени у текста и установлено по умолчанию.
Цвет тени задается в любом доступном CSS формате и является не обязательным параметром. По умолчанию цвет тени совпадает с цветом текста.
Горизонтальное смещение тени можно задавать в любой единице измерения поддерживаемой CSS. При положительном значении тень будет располагаться правее текста, при отрицательном — левее. Нулевое значение расположит тень прямо под текстом и имеет смысл только если задано размытие тени.
Вертикальное смещение тени тоже можно задавать в любой единице измерения поддерживаемой CSS. При положительном значении тень будет смещаться ниже текста, при отрицательном — выше. Нулевое значение расположит тень прямо под текстом.
В любой единице измерения задается и радиус размытия тени . Чем больше это значение, тем шире становится тень и сильнее сглаживается. Если этот параметр не установлен, то значение размытие предполагается равным нулю. Так как алгоритм сглаживания обычно у разных браузеров отличается, то и вид тени может несколько отличаться в зависимости от браузера.
Задаёт выравнивание последней строки блока текста.
Краткая информация
Обозначения
Описание | Пример | |
---|---|---|
<тип> | Указывает тип значения. | <размер> |
A && B | Значения должны выводиться в указанном порядке. | <размер> && <цвет> |
A | B | Указывает, что надо выбрать только одно значение из предложенных (A или B). | normal | small-caps |
A || B | Каждое значение может использоваться самостоятельно или совместно с другими в произвольном порядке. | width || count |
Группирует значения. | [ crop || cross ] | |
* | Повторять ноль или больше раз. | [,<время>]* |
+ | Повторять один или больше раз. | <число>+ |
? | Указанный тип, слово или группа не является обязательным. | inset? |
{A, B} | Повторять не менее A, но не более B раз. | <радиус>{1,4} |
# | Повторять один или больше раз через запятую. | <время># |
Значения
auto Совпадает с выравниванием, заданным свойством text-align , за исключением значения justify . Для него выравнивание будет как start . start Строка выравнивается по начальному краю блока, который может меняться в зависимости от направления текста (слева направо или справа налево). end Строка выравнивается по конечному краю блока, он определяется направлением текста. left Строка выравнивается по левому краю. right Строка выравнивается по правому краю. center Строка выравнивается по центру. justify Строка выравнивается по ширине. Если в последней строке только одно слово, то оно будет выравнено по левому краю.
Влияние разных значений на положение текста показано в табл. 1.
Значение | Выравнивание | Вид текста |
---|---|---|
left | По левому краю | |
right | По правому краю | |
center | По центру | |
justify | По ширине |
Песочница
Винни-Пух был всегда не прочь немного подкрепиться, в особенности часов в одиннадцать утра, потому что в это время завтрак уже давно окончился, а обед ещё и не думал начинаться. И, конечно, он страшно обрадовался, увидев, что Кролик достаёт чашки и тарелки.
div { text-align-last: start ; }
Пример
Object Model
An object.style.textAlignLast
Note
Internet Explorer and Edge do not support start and end values.
Firefox version 49 supports the -moz-text-align-last property.
Specification
Each specification goes through several stages of approval.
- Recommendation - This specification has been endorsed by the W3C and is recommended as a standard.
- Candidate Recommendation ( Possible recommendation) - the group responsible for the standard is satisfied that it is in line with its objectives, but the help of the developer community is required to implement the standard.
- Proposed Recommendation ( Suggested recommendation) - At this point, the document is submitted to the W3C Advisory Council for final approval.
- Working Draft - A more mature version of the draft after discussion and amendments for community review.
- Editor "s draft ( Editorial draft) - a draft version of the standard after editing by the project editors.
- Draft ( Draft specification) is the first draft of the standard.
Module Css text describes the CSS functions that control the translation of source text into formatted text and line wrapping. Various CSS properties provide control over case conversion, handling of whitespace, hyphenation and wrapping rules for text and lines, alignment, spacing, and indentation.
The basic unit of text is a symbol. However, since writing systems are not always as simple as the mainstream English alphabet, what a symbol actually is depends on the context in which the term is used. For example, in the Korean writing system, each square representation of a syllable (for example, 한 = han) can be considered a symbol. However, a square symbol does indeed consist of multiple letters, each representing a phoneme (for example, ㅎ = h, ㅏ = a, ㄴ = n), and each of them can also be considered a symbol.
1. Transforming text: the text-transform property
The text-transform property will style the text. It does not affect the underlying content, and should not affect the content of a plain text copy and paste operation.
The property is inherited.
Syntax
Text-transform: none; text-transform: capitalize; text-transform: uppercase; text-transform: lowercase; text-transform: inherit; text-transform: initial;
2. Handling spaces and line breaks: the white-space property
The white-space property handles white space and line breaks within an element.
The property is inherited.
white-space | |
---|---|
Values: | |
normal | Default value. Only one space is inserted between words, additional spaces are discarded. The text is wrapped only if necessary. |
nowrap | Prevents line breaks except when applied . |
pre | Spaces in the text are not ignored; the browser displays extra spaces and line breaks. |
pre-wrap | Preserves spaces in the text by making line breaks where appropriate. |
pre-line | Removes extra spaces except for cases . |
break-spaces | The behavior is identical to pre-wrap, except that: any sequence of non-removable whitespace always takes up space, including at the end of a line; the line break option exists after each non-removable space, including between spaces. |
initial | |
inherit |
Syntax
White-space: normal; white-space: nowrap; white-space: pre; white-space: pre-wrap; white-space: pre-line; white-space: break-spaces; white-space: inherit; white-space: initial;
3. Setting tabs: the tab-size property
The tab-size property is used to change the amount of indentation obtained with the Tab key. Property values are ignored when one of the three pre-line, normal, or nowrap values of the white-space property is set.
Only works for elements
The property is inherited.
Syntax
Tab-size: 0; tab-size: 10px; tab-size: inherit; tab-size: initial;
4. Line break and word boundaries
When line-level content is broken into lines, it is broken into linear blocks. This splitting is called a line break.
When a line breaks due to explicit line break controls such as newline or tag
, start or end of a block is a forced line break.
If a line breaks due to content wrapping when the browser creates optional line breaks to fit the content, it is soft wrapping.
4.1. Letter break rules: the word-break property
The word-break property defines the possibilities of soft wrap between letters, i.e. when it is permissible to split lines of text. In particular, it controls whether soft hyphenation exists between adjacent typographic letter units and / or numbers. This does not affect the rules governing the soft hyphenation capabilities created by spaces.
The property is inherited.
Syntax
Word-break: normal; word-break: break-all; word-break: keep-all; word-break: inherit; word-break: initial;
4.2. Line break: line-break
The line-break property defines the rules for line wrapping applied within an element, in particular how the wrapping interacts with punctuation marks and symbols.
The property is inherited.
line-break | |
---|---|
Values: | |
auto | The browser defines a set of line break constraints to use, which can vary based on line length, such as using a less stringent set of line break rules for short lines. Default value. |
loose | Breaks up text using the least restrictive set of line wrapping rules. Typically used for short lines, such as in newspapers. |
normal | Breaks up text using the most common set of line wrapping rules. |
strict | Breaks up text using a strict set of line wrapping rules. |
initial | Sets the property value to its default value. |
inherit | Inherits the property value from the parent element. |
Syntax
Line-break: auto; line-break: loose; line-break: normal; line-break: strict; line-break: inherit; line-break: initial;
4.3. Hyphenation: the hyphens property
The hyphens property determines whether hyphens are allowed to create soft hyphenation capabilities within a line of text.
Hyphenation is controlled word-breaking, in which words are usually not allowed to break in order to improve the layout of paragraphs. As a rule, word splitting occurs along syllabic or morphemic boundaries and with visual indication of separation (usually by inserting a hyphen, -). In some cases, hyphenation can also change the spelling of a word. In any case, word wrap is only a rendering effect: it should not affect document content, text selection or search.
CSS Text Level 3 does not define precise hyphenation rules, so it is recommended that you choose hyphenation points that are appropriate for your language.
The property is inherited.
hyphens | |
---|---|
Values: | |
none | Words are not hyphenated, even if the characters within the word explicitly define hyphenation. |
manual | Words are hyphenated only in those places where there are characters inside the word that clearly indicate the possibility of word hyphenation ( special character-). Default value. |
auto | Words can be split into hyphenation capabilities, as determined automatically by the language-appropriate hyphenation resource, in addition to those explicitly indicated by a hyphenated hyphen. You need to set the language of your content (for example, using the HTML lang attribute or the HTTP Content-Language header) in order to get proper auto-word wrapping. |
initial | Sets the property value to its default value. |
inherit | Inherits the property value from the parent element. |
Syntax
Hyphens: none; hyphens: manual; hyphens: auto; hyphens: inherit; hyphens: initial;
4.4. Wrap-block overflow: overflow-wrap / word-wrap property
The overflow-wrap property (or its deprecated name word-wrap) specifies whether a non-breaking line can break at unresolved points to prevent a line box from overflowing. Works when the white-space property allows wrapping.
The property is inherited.
overflow-wrap, word-wrap | |
---|---|
Values: | |
normal | Non-breaking lines can only break at permitted breakpoints. Default value. |
break-word | |
anywhere | A contiguous sequence of characters can be broken at an arbitrary point if there are no other acceptable break points in the line. Affects only visual display without affecting the original text. No new line is added at the line break point. The soft wrap options provided anywhere are considered when calculating your own minimum content sizes. |
initial | Sets the property value to its default value. |
inherit | Inherits the property value from the parent element. |
Syntax
Overflow-wrap: normal; overflow-wrap: break-word; overflow-wrap: anywhere; overflow-wrap: inherit; overflow-wrap: initial;
5. Aligning and justifying lines
The alignment and justification of lines controls how inline content is distributed in a line box.
5.1. A shorthand for aligning text: the text-align property
A block of text is a collection of linear blocks. The text-align property specifies the text-align-all and text-align-last properties and describes how the line-level boxes in each line box are aligned relative to the start and end sides of the line box. Values other than justify-all or match-parent are assigned to text-align-all and reset in text-align-last to auto.
The property is inherited.
text-align | |
---|---|
Values: | |
start | Line-level content is aligned with the start edge of the line box. Default value. |
end | Line-level content is aligned to the trailing edge of the line box. |
left | Line-level content is aligned to the left of the line box line. In vertical writing systems, this will be the physical top or bottom, depending on the orientation of the text. |
right | Row-level content is right-aligned on the line box of the inline box. In vertical writing systems, this will be the physical top or bottom, depending on the orientation of the text. |
center | Line-level content is centered within the line box. |
justify | The text is aligned to the width of the inline box to precisely fill the line box, snuggling to the left and right edges of the parent element. Unless otherwise specified in text-align-last, the last line before a forced break or the end of a block is aligned to the beginning. Spaces between words and letters are distributed in such a way that the length of all lines is equal. Different browsers can increase both the spacing between words and the spacing between letters. |
justify-all | Sets text-align-all and text-align-last to justify, also aligning the last line. |
match-parent | The value behaves the same as inherit, except that the inherited start or end value is interpreted relative to the direction value (or the original containing block if there is no parent) and results in the computed value of left or right. |
inherit | Inherits the property value from the parent element. |
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: inherit;
5.2. Default text alignment: text-align-all property
The text-align-all property is a shorthand version of the text-align property that determines the alignment of all lines of content in a block container, except for the last lines, which are overridden by text-align-last. Accepts the values start, end, left, right, center, justify, and match-parent.
The property is inherited.
Syntax
Text-align-all: start; text-align-all: end; text-align-all: left; text-align-all: right; text-align-all: center; text-align-all: justify; text-align-all: match-parent; text-align-all: inherit;
5.3. Align the last line: the text-align-last property
The text-align-last property describes how the last line of a block or line is aligned immediately before a forced line break.
If set to auto, the content on the corresponding line is aligned with text-align-all, unless justify is set for text-align-all, in which case it is aligned to the start of the block. All other values are interpreted as described for text-align.
The values are auto, start, end, left, right, center, justify, and match-parent.
The property is inherited.
Syntax
Text-align-last: auto; text-align-last: start; text-align-last: end; text-align-last: left; text-align-last: right; text-align-last: center; text-align-last: justify; text-align-last: match-parent;
6. Gaps
CSS allows you to control the spacing between words and typographic characters using the word-spacing and letter-spacing properties.
6.1. Spacing between words: the word-spacing property
The word-spacing property defines additional spacing between words.
Sets the spacing between words. Positive and negative values can be used. With a negative meaning, words can overlap.
The value of word-spacing is affected by the value of the text-align property when text is aligned to width.
The property is inherited.
Syntax
Word-spacing: normal; word-spacing: 1px; word-spacing: 0.2em; word-spacing: 50%; word-spacing: inherit; word-spacing: initial;
6.2. Tracking: the letter-spacing property
The letter-spacing property specifies additional spacing, or tracking, between adjacent typographic characters. Letter spacing is complementary to and word-spacing. User agents can further increase or decrease the spacing between typographic character units for text alignment, depending on current alignment rules.
The property is inherited.
Syntax
Letter-spacing: normal; letter-spacing: 0.1em; letter-spacing: 2px; letter-spacing: inherit; letter-spacing: initial;
7. First line indent: text-indent property
The text-indent property specifies the indentation applied to lines of inline content in a block. The padding is treated as a margin applied to the start edge of the line box.
If there is an image in the first line of a block element, then it will move along with the rest of the text.
The property is inherited.
Syntax
Text-indent: 5mm; text-indent: 20px; text-indent: 5%; text-indent: 2em each-line; text-indent: 2em hanging; text-indent: inherit; text-indent: initial;