- Выравнивание текста
- How to Align Text in HTML – Text-align, Center, and Justified Example
- How to Align Text to Center Before HTML5
- How to Align Text in HTML5
- How to align text to the left
- How to align text to the right
- How to align text to the center
- How to justify text
- Wrapping Up
- CSS text-align Property
- Browser Support
- CSS Syntax
- Property Values
- More Examples
- Example
- Related Pages
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
Выравнивание текста
Выравнивание текста определяет его внешний вид и ориентацию краев абзаца и может выполняться по левому краю, правому краю, по центру или по ширине. В табл. 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 Align Text in HTML – Text-align, Center, and Justified Example
Joel Olawanle
Text is essential on web pages, as it tells your users what your web page is all about.
When you add text to your web page, it dictates the direction and feel of your web page based on your language.
For example, by default, English moves from left to right (LTR), while Arabic moves from right to left (RTL).
But most times, you won’t want all your text to remain in only one position of your screen or container. You will want some to be in the center, some to the left, and others to the right. You might even want the text to fill up your page or container.
This is similar to what you do when editing texts in Microsoft Word or Google Docs, using the left align, right align, center, and justify buttons.
You can also do the same on your web pages using code.
How to Align Text to Center Before HTML5
Before the introduction of HTML5, developers performed specific styling with HTML tags. For example, you could use the center tag to align your text to the center, but in HTML4, this tag got depreciated. Although this may still work with some major browsers, it might get dropped at any point.
Welcome to freeCodeCamp
Lorem ipsum dolor sit amet consectetur adipisicing elit. Architecto, inventore. Culpa, rerum neque. Necessitatibus quod velit vitae unde sed? Expedita consequuntur ea quis reiciendis nobis distinctio quod deserunt doloremque in. Lorem ipsum dolor sit amet consectetur adipisicing elit. Architecto, inventore. Culpa, rerum neque. Necessitatibus quod velit vitae unde sed? Expedita consequuntur ea quis reiciendis nobis distinctio quod deserunt doloremque in.
How we work
Lorem ipsum dolor sit amet consectetur adipisicing elit. Architecto, inventore. Culpa, rerum neque. Necessitatibus quod velit vitae unde sed? Expedita consequuntur ea quis reiciendis nobis distinctio quod deserunt doloremque in.
This will output all our text in the center of the page or whatever container it is applied to:
But now that we have HTML5, we don’t use this method anymore. Remember that it’s essential to always handle all stylings with CSS. You should use HTML only to add markup to your web page.
How to Align Text in HTML5
With CSS, you have many options that you can use to align your text. The major CSS property that works well with text alignment is the text-align property. You use this property to specify the horizontal alignment of text in an element.
Suppose you have some text on your web page, for example:
Welcome to freeCodeCamp
Lorem ipsum dolor sit amet consectetur adipisicing elit. Architecto, inventore. Culpa, rerum neque. Necessitatibus quod velit vitae unde sed? Expedita consequuntur ea quis reiciendis nobis distinctio quod deserunt doloremque in. Lorem ipsum dolor sit amet consectetur adipisicing elit. Architecto, inventore. Culpa, rerum neque. Necessitatibus quod velit vitae unde sed? Expedita consequuntur ea quis reiciendis nobis distinctio quod deserunt doloremque in.
How we work
Lorem ipsum dolor sit amet consectetur adipisicing elit. Architecto, inventore. Culpa, rerum neque. Necessitatibus quod velit vitae unde sed? Expedita consequuntur ea quis reiciendis nobis distinctio quod deserunt doloremque in.
You can use the text-align property to move the text to the left, right, center, or even justify your content, so it fills the element or web page horizontally.
// Syntax text-align: start; text-align: end; text-align: left; text-align: right; text-align: center; text-align: justify;
If you want to align the entire text on your web page, you can apply this property to any tag containing the text, such as the div tag, heading, paragraph, or body tag.
Before seeing an example, let’s explore the available options/values for this property.
- start : This is based on the direction. When the direction is left-to-right, start would mean left . If the direction is right-to-left, then start would mean right .
- end : This is also based on the direction. When the direction is left-to-right, then end would mean right. If the direction is right-to-left, then end would mean left.
- left : You use this to align the texts to the left edge of the page or container.
- right : You use this to align the texts to the right edge of the page or container.
- center : You use this to align the texts to the perfect center of the page or container.
- justify : You use this to adjust the text content to touch the left and right edges of your page or container.
The general syntax would be:
How to align text to the left
You might need to switch the alignment of your text to the left if it is originally on the right side. You do this by targeting the selector and using the text-align property alongside left as its value.
// HTMLWelcome to freeCodeCamp
// CSS p
For example, if you have your content from the right of your screen using the RTL direction:
Welcome to freeCodeCamp
Lorem ipsum dolor sit amet consectetur adipisicing elit. Architecto, inventore. Culpa, rerum neque. Necessitatibus quod velit vitae unde sed? Expedita consequuntur ea quis reiciendis nobis distinctio quod deserunt doloremque in. Lorem ipsum dolor sit amet consectetur adipisicing elit. Architecto, inventore. Culpa, rerum neque. Necessitatibus quod velit vitae unde sed? Expedita consequuntur ea quis reiciendis nobis distinctio quod deserunt doloremque in.
How we work
Lorem ipsum dolor sit amet consectetur adipisicing elit. Architecto, inventore. Culpa, rerum neque. Necessitatibus quod velit vitae unde sed? Expedita consequuntur ea quis reiciendis nobis distinctio quod deserunt doloremque in.
You can style the body tag to align the page’s text to the left :
How to align text to the right
By default, your web page or content in the container and other elements start from the left. You might want to align this content to the right, which is accessible using the text-align property with a value right .
// HTMLWelcome to freeCodeCamp
// CSS p
How to align text to the center
Instead of using the center tag to move our text content to the center, you can now use the text-align property alongside the center value to move your text to the center.
// HTMLWelcome to freeCodeCamp
// CSS p
How to justify text
If you know how to use any text-based tool like Microsoft Word or Google Docs, or tools like Photoshop, Figma, and many more that handle content, you will know how the justify text icon works.
You use it to help your text go up to the edges of a page/container rather than having some unnecessary uneven spaces at the end.
This is not always obvious, but when you take a deep look at the edges, you’ll notice the difference, which makes more sense when you have so much text and longer paragraphs.
You do this by using the text-align property alongside justify as its value:
// HTMLLorem ipsum dolor sit amet consectetur adipisicing elit. Architecto, inventore. Culpa, rerum neque. Necessitatibus quod velit vitae unde sed? Expedita consequuntur ea quis reiciendis nobis distinctio quod deserunt doloremque in.
// CSS p
Wrapping Up
In this article, you have learned how to align the text of your HTML web page using text-align CSS property.
You can learn more via other similar articles that have been published on freeCodeCamp:
Embark on a journey of learning! Browse 200+ expert articles on web development. Check out my blog for more captivating content from me.
CSS text-align Property
The text-align property specifies the horizontal alignment of text in an element.
Default value: | left if direction is ltr, and right if direction is rtl |
---|---|
Inherited: | yes |
Animatable: | no. Read about animatable |
Version: | CSS1 |
JavaScript syntax: | object.style.textAlign=»right» Try it |
Browser Support
The numbers in the table specify the first browser version that fully supports the property.
CSS Syntax
Property Values
Value | Description | Demo |
---|---|---|
left | Aligns the text to the left | Demo ❯ |
right | Aligns the text to the right | Demo ❯ |
center | Centers the text | Demo ❯ |
justify | Stretches the lines so that each line has equal width (like in newspapers and magazines) | Demo ❯ |
initial | Sets this property to its default value. Read about initial | |
inherit | Inherits this property from its parent element. Read about inherit |
More Examples
Example
Another text-align example:
Related Pages
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.