Название документа

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

Источник

CSS: Выравнивание текста

По умолчанию текст на веб-страницах выровнен по левому краю элемента, в котором он располагается, однако используя свойство text-align, можно переопределить, как будут выравниваться строки текста относительно границ элемента. Рассмотрим каждое из возможных значений:

  • left — выравнивает текст по левому краю.
  • right — выравнивает текст по правому краю.
  • center — выравнивает текст по центру.
  • justify — выравнивает текст по ширине, в таком тексте оба конца строки размещаются вплотную к внутренним краям элемента. Пробелы между словами в этом случае корректируются браузером так, что бы длина всех строк была строго одинаковая.

       

Пример выравнивания текста

февраль, 2012

Помимо выравнивания текста, для первой строки абзаца был задан небольшой отступ, который визуально добавляет "красную строку" к тексту. Этот эффект очень пригодится на страницах с большими объемами текста, облегчая визуальное восприятие.

Примечание: свойство text-align работает только с блочными элементами, такими как абзац или div, выравнивая внутри них все строчное содержимое, включая изображения. Применение свойства к строчным элементам, таким как ссылка или span, не даст никакого эффекта.

Читайте также:  Javascript form serialize object

Копирование материалов с данного сайта возможно только с разрешения администрации сайта
и при указании прямой активной ссылки на источник.
2011 – 2023 © puzzleweb.ru

Источник

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
Читайте также:  Input type image src php

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; > 

Источник

text — align

Выравниваем текст по левому или правому краю. А может быть по центру?

Время чтения: меньше 5 мин

Кратко

Скопировать ссылку «Кратко» Скопировано

text — align выравнивает текст по горизонтали внутри блока.

Если это свойство не задано, то текст выравнивается по левому краю.

Примеры

Скопировать ссылку «Примеры» Скопировано

 p  text-align: center;> p  text-align: center; >      

Специальные значения для столбца в таблице:

 p  text-align: '.'; text-align: '.' center;> p  text-align: '.'; text-align: '.' center; >      

Выравнивание блока (нестандартный синтаксис):

 p  text-align: -moz-center; text-align: -webkit-center;> p  text-align: -moz-center; text-align: -webkit-center; >      

Как пишется

Скопировать ссылку «Как пишется» Скопировано

У text — align есть четыре варианта значений:

  • center — выравнивание по центру.
  • justify — выравнивание по ширине. Текст растягивается от левого до правого края, между словами появляются большие пробелы.
  • left — выравнивание по левому краю (значение по умолчанию).
  • right — выравнивание по правому краю.

Не так давно появилось ещё два крайне удобных значения:

  • start — текст выровнен по тому краю, по которому принято в текущем языке.
  • end — текст выровнен по противоположному краю для текущего языка.

Формулировки сложные, но на самом деле всё просто. Если в русском мы читаем слева направо, то значение start будет выравнивать текст по левому краю, а end — по правому. Но в некоторых языках текст читается наоборот, справа налево. В этому случае start выровняет текст по правому краю, а end по левому. При этом вам ничего не нужно будет изменять. Значения сами подстроятся под текст. Достаточно изменить значение атрибута lang у тега . Эти значения очень удобны, если вы разрабатываете мультиязычные сайты или приложения.

Подсказки

Скопировать ссылку «Подсказки» Скопировано

💡 Значение свойства наследуется.

💡 Значение по умолчанию — left .

💡 Хотите отцентровать блок, не меняя выравнивание внутри него? Добавьте левый и правый отступ margin со значением auto : например, margin : auto , margin : 0 auto , margin — left : auto; margin — right : auto , margin — inline : auto .

💡 Выравнивание текста нельзя анимировать при помощи transition ☹️

Ещё пример

Скопировать ссылку «Ещё пример» Скопировано

   
Выравнивание по левому краю
Выравнивание по центру
Выравнивание по правому краю
div class="left"> div class="content">Выравнивание по левому краюdiv> div> div class="center"> div class="content">Выравнивание по центруdiv> div> div class="right"> div class="content">Выравнивание по правому краюdiv> div>
 .left  text-align: left;> .right  text-align: right;> .center  text-align: center;> .left  text-align: left; > .right  text-align: right; > .center  text-align: center; >      

На практике

Скопировать ссылку «На практике» Скопировано

Алёна Батицкая советует

Скопировать ссылку «Алёна Батицкая советует» Скопировано

🛠 Свойство text — align можно использовать не только для выравнивания текста в строчных элементах, но и для выравнивания строчно-блочных ( inline — block ) элементов внутри родителя.

С появлением флексбоксов такое решение теряет свою популярность, но знать о нём стоит.

Простая разметка из родительского блока и трёх строчно-блочных вложенных элементов:

   
🙈
🙉
🙊
div class="parent"> div class="child">🙈div> div class="child">🙉div> div class="child">🙊div> div>
 .parent  width: 80%; margin: 0 auto; padding: 25px;> .child  display: inline-block; /* Меняем отображение на строчно-блочное */ width: 125px; height: 125px; padding: 25px; text-align: center; /* Выравниваем текст внутри блоков */ font-size: 75px; line-height: 1; font-weight: bold;> .parent  width: 80%; margin: 0 auto; padding: 25px; > .child  display: inline-block; /* Меняем отображение на строчно-блочное */ width: 125px; height: 125px; padding: 25px; text-align: center; /* Выравниваем текст внутри блоков */ font-size: 75px; line-height: 1; font-weight: bold; >      

Добавим элементу .parent свойство text — align : center и элементы .child выровняются по центру родителя:

А если попробовать распределить вложенные элементы равномерно по ширине родителя, задав text — align : justify ?

Ожидаемого поведения не получилось, и вот почему 👇

🛠 У значения justify хитрая логика. Чтобы можно было равномерно распределить элементы внутри родителя нужно задать этому самому родителю пустой строчно-блочный псевдоэлемент с шириной 100%.

 .parent::after  content: ''; display: inline-block; width: 100%;> .parent::after  content: ''; display: inline-block; width: 100%; >      

Источник

Оцените статью