- text-align
- Синтаксис
- Значения
- Объектная модель
- Браузеры
- CSS Layout — Horizontal & Vertical Align
- Example
- Center Align Text
- Example
- Center an Image
- Example
- Left and Right Align — Using position
- Example
- Left and Right Align — Using float
- Example
- The clearfix Hack
- Without Clearfix
- With Clearfix
- Example
- Center Vertically — Using padding
- Example
- Example
- Center Vertically — Using line-height
- Example
- Center Vertically — Using position & transform
- Example
- Center Vertically — Using Flexbox
- Example
- 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
text-align
Определяет горизонтальное выравнивание текста в пределах элемента.
Синтаксис
text-align: center | justify | left | right | inherit
text-align: center | justify | left | right | start | end
Значения
center Выравнивание текста по центру. Текст помещается по центру горизонтали окна браузера или контейнера, где расположен текстовый блок. Строки текста словно нанизываются на невидимую ось, которая проходит по центру веб-страницы. Подобный способ выравнивания активно используется в заголовках и различных подписях, вроде подрисуночных, он придает официальный и солидный вид оформлению текста. Во всех других случаях выравнивание по центру применяется редко по той причине, что читать большой объем такого текста неудобно. justify Выравнивание по ширине, что означает одновременное выравнивание по левому и правому краю. Чтобы произвести это действие браузер в этом случае добавляет пробелы между словами. left Выравнивание текста по левому краю. В этом случае строки текста выравнивается по левому краю, а правый край располагается «лесенкой». Такой способ выравнивания является наиболее популярным на сайтах, поскольку позволяет пользователю легко отыскивать взглядом новую строку и комфортно читать большой текст. right Выравнивание текста по правому краю. Этот способ выравнивания выступает в роли антагониста предыдущему типу. А именно, строки текста равняются по правому краю, а левый остается «рваным». Из-за того, что левый край не выровнен, а именно с него начинается чтение новых строк, такой текст читать труднее, чем, если бы он был выровнен по левому краю. Поэтому выравнивание по правому краю применяется обычно для коротких заголовков объемом не более трех строк. Мы не рассматриваем специфичные сайты, где текст приходится читать справа налево, там возможно подобный способ выравнивания и пригодится. auto Не изменяет положение элемента. inherit Наследует значение родителя. start Аналогично значению left , если текст идёт слева направо и right , когда текст идёт справа налево. end Аналогично значению right , если текст идёт слева направо и left , когда текст идёт справа налево.
HTML5 CSS2.1 IE Cr Op Sa Fx
Результат данного примера показан на рис. 1.
Рис. 1. Выравнивание текста в браузере Safari
Internet Explorer до версии 7.0 включительно несколько иначе трактует данный пример, чем другие браузеры, выравнивая не только текст, но и блоки (рис. 2).
Рис. 2. Выравнивание текста в браузере Internet Explorer 7
Объектная модель
[window.]document.getElementById(» elementID «).style.textAlignБраузеры
IE до версии 7.0 включительно выравнивает не только содержимое блочного элемента, но и сам элемент.
CSS Layout — Horizontal & Vertical Align
Setting the width of the element will prevent it from stretching out to the edges of its container.
The element will then take up the specified width, and the remaining space will be split equally between the two margins:
This div element is centered.
Example
Note: Center aligning has no effect if the width property is not set (or set to 100%).
Center Align Text
To just center the text inside an element, use text-align: center;
Example
Tip: For more examples on how to align text, see the CSS Text chapter.
Center an Image
To center an image, set left and right margin to auto and make it into a block element:
Example
Left and Right Align — Using position
One method for aligning elements is to use position: absolute; :
In my younger and more vulnerable years my father gave me some advice that I’ve been turning over in my mind ever since.
Example
Note: Absolute positioned elements are removed from the normal flow, and can overlap elements.
Left and Right Align — Using float
Another method for aligning elements is to use the float property:
Example
The clearfix Hack
Note: If an element is taller than the element containing it, and it is floated, it will overflow outside of its container. You can use the «clearfix hack» to fix this (see example below).
Without Clearfix
With Clearfix
Then we can add the clearfix hack to the containing element to fix this problem:
Example
Center Vertically — Using padding
There are many ways to center an element vertically in CSS. A simple solution is to use top and bottom padding :
Example
To center both vertically and horizontally, use padding and text-align: center :
I am vertically and horizontally centered.
Example
Center Vertically — Using line-height
Another trick is to use the line-height property with a value that is equal to the height property:
I am vertically and horizontally centered.
Example
.center <
line-height: 200px;
height: 200px;
border: 3px solid green;
text-align: center;
>
/* If the text has multiple lines, add the following: */
.center p line-height: 1.5;
display: inline-block;
vertical-align: middle;
>
Center Vertically — Using position & transform
If padding and line-height are not options, another solution is to use positioning and the transform property:
I am vertically and horizontally centered.
Example
.center <
height: 200px;
position: relative;
border: 3px solid green;
>
.center p margin: 0;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
>
Tip: You will learn more about the transform property in our 2D Transforms Chapter.
Center Vertically — Using Flexbox
You can also use flexbox to center things. Just note that flexbox is not supported in IE10 and earlier versions:
Example
.center <
display: flex;
justify-content: center;
align-items: center;
height: 200px;
border: 3px solid green;
>
Tip: You will learn more about Flexbox in our CSS Flexbox Chapter.
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.