Align text to center with CSS

In the first versions of HTML there was the align attribute, which, through different values, allowed us to align the text to the left, center or right. With the arrival of style sheets CSS this attribute becomes obsolete and the alignment becomes controlled by attributes CSS. In this example we are going to see how we can align text to the center with CSS.

The property CSS that allows us to align the text is
text-align
. We can apply this property to the different elements HTML that manage blocks: headers, paragraphs, layers,…

The syntax of the
text-align
is the following:

text-align : start | end | left | right | center | justify | match-parent | justify-all

Thus, the values ​​it can take
text-align
are:

  • justify, Justifies the content inside the box of all lines except the last one.
  • justify-all, Justifies the content inside the box of all lines including the last one.
  • match-parent, Accepts the alignment that the parent element has.
  • end, Pays attention to the direction of the text. If it is a left-right text, it aligns it to the right and if it is a right-left text, it aligns it to the left.
  • center, Centers the text inside the box.
  • left, Aligns the text to the left of the box.
  • start, Pay attention to the direction of the text. If it is a left-right text, it aligns it to the left and if it is a right-left text, it aligns it to the right.
  • right, Aligns the text to the right of the box.

In case you want to align text to the center with CSS we must use the value
center
. So, for example, we can apply it to a header. The first thing we will have to do is define a style sheet in the header of the page

h2.center{
  text-align: center;
}

Then we will simply have to use the center class inside an element
h2
. To do this we use the class attribute.

<h2 class="center">Centered header</h2>

I hope this simple example to align text to the center with CSS.