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!