How to vertical align text or other elements with CSS

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Horizontal centering of text or other content should not be a problem for most people. Vertical centering is a different matter, and some people have certainly lost countless nerves. ? In this article, I will introduce you to two ways to vertically center elements with little code.

Important: To vertically center elements with these methods, the element to be centered must be the only direct child element of a parent element. It must not contain any other sibling elements.

Option 1. display: table

This option has very good browser support and should not be confused with tables, with which entire layouts were developed at that time. This is about the “display:table” property of CSS. So you can breathe a sigh of relief. ?

Example for the HTML structure:


Now the corresponding CSS code follows. You give your parent element “display: table” so that it behaves like a table in HTML. Please note that if this element is a block element, the width of 100% must be added manually. (width: 100%;)

The child element receives the values display: table-cell and vertical-align: middle. The first value causes the child element to behave like a table row in HTML, the second value vertically centers the row relative to the parent element.

Example for the CSS statements


That’s it. Now the content of the element should be displayed vertically centered using the class kind-element. Let’s now look at the second possibility.

Option 2. display: flex

I especially like this possibility, because you only have to give instructions to the parent element. The disadvantage is the browser support. Older browsers unfortunately do not support the Flexbox model, so please check the requirements of your project before you decide to use this option.

With the specification display: flex the flexbox model is activated within an element. If you want the content of this element to be vertically centered, use align-items: center. For horizontal centering, use justify-content: center. The HTML structure remains:

Example for the HTML structure:


Example for the CSS statements


Well, that would have centered the content vertically.

Have fun trying it out!

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore

ins Konto einloggen

Diese Website verwendet Cookies, um sicherzustellen, dass Sie die bestmögliche Erfahrung auf unserer Website erzielen. Erfahren Sie mehr