Centering HTML elements is an important aspect for anything involving designing with CSS. There are various methods of centering things, however, it also depends on the elements that you are working with. In this series, we will go over the matter of how to center different elements horizontally and vertically.
Here, we will start with a simple task of centering a text inside another HTML elements - a div. You can follow this series by the links to the next post provided at the end of this article.
1. How to center a text horizontally?
To center a text or a link horizontally, we need to use text-align property with the value center :
HTML:
<div class="outer-wrap"> Hello, The World is Horizontally Centered! </div>
CSS:
.outer-wrap { text-align: center; border: 1px dashed black; }
Result:
2. How to center a text vertically?
Center things vertically is more difficult than doing it horizontally. Below are 2 methods of centering a text or a paragraph vertically:
a. Using the line-height property
The important thing of this method is:
- the height of an outer element must be a fixed height.
- the line-height value has to be same as the height of the outer element.
HTML:
<div class="outer-wrap"> Hello, The World is Vertically Centered! </div>
CSS:
.outer-wrap { height: 100px; line-height: 100px; border: 1px dashed black; }
Result:
Problem: Longer text causes multiple lines. Because the line-height is 100px which causes the total height of the text greater than the outer element. So, the second line is outside of the outer element.
Solution: wrap the text inside another element (span or div or p) and add below css property:
HTML:
<div class="outer-wrap"> <span class="inner-text">Hello, The World is Vertically Centered! The problem of a multiple-line text or a long text is solved in this solution! Let's see if it works with this loooooooooooong teeeeeexxxxttttttttt! </span> </div>
CSS:
.outer-wrap { height: 100px; line-height: 100px; border: 1px dashed black; } .inner-text{ display: inline-block; vertical-align: middle; line-height: normal; }
Result:
b. Using the flex box
HTML:
<div class="outer-wrap"> <span>Hello, The World is Vertically Centered!</span> </div>
CSS:
.outer-wrap { display: flex; align-items: center; height: 100px; border: 1px dashed black; }
Result:
3. How to center a text horizontally and vertically?
So, we can combine the CSS properties above to make the text centered horizontally and vertically:
a. Using line-height property
HTML:
<div class="outer-wrap"> <span class="inner-text">Hello, The World is Centered! </span> </div>
CSS:
.outer-wrap { height: 100px; line-height: 100px; text-align: center; border: 1px dashed black; } .inner-text{ display: inline-block; vertical-align: middle; line-height: normal; }
Result
b. Using flex box
HTML:
<div class="outer-wrap"> <span>Hello, The World is Centered!</span> </div>
CSS:
.outer-wrap { display: flex; justify-content: center; align-items: center; height: 100px; border: 1px dashed black; }