Aligning Items Vertically
For many years, aligning elements perfectly in the vertical center of their containers was a notoriously frustrating task in web development. Today, thanks to CSS Flexbox, aligning items vertically is incredibly simple.
You can vertically center any element (text, images, or entire div blocks) inside a container by applying just two lines of CSS to the parent container.
Using Flexbox for Vertical Alignment
To align an element vertically with Flexbox, you must turn its parent container into a flex container using display: flex. Once that is done, simply apply the align-items property and set its value to center.
The align-items property controls alignment across the "cross axis" (which, by default, is top-to-bottom):
Perfect Dead-Center Alignment
If you want to center an element both vertically and horizontally, you simply add the justify-content property (which controls the left-to-right axis) and also set it to center:
Full Working Example
Below is a working example demonstrating a blue box perfectly suspended in the dead center of a larger 300-pixel tall container: