DEV Community

Wassim SAMAD
Wassim SAMAD

Posted on

Full height sections perfectly centered with flex

Hello Dev community! This is my first post here and as this place is a great source of inspiration for me I wanted to take part of it. Let's go!

Introduction

Have you ever needed to display perfectly centered (vertically and horizontally) content on your sections whatever the content height is? There are multiple options to achieve this but my favorite one is to use flexbox.

A long time ago I would have done display table-cell and vertical-align middle, but come on... Web evolves (and so do I)!

Flex

Display flex provides you easy ways to center the content both horizontally and vertically of an HTML element:

align-items: center; // for vertical alignment
justify-content: center; // for horizontal alignment

To go deeper into flexbox go to https://www.w3schools.com/css/css3_flexbox.asp

Flex direction

By default, the flex-direction of an element is set to row which means its direct children will act as columns in a row displayed horizontally. You can decide to do the opposite by setting flex-direction to column so its direct children will be displayed as the content of a column: one above the other.

Note that using flex-direction column align-items and justify-content will be inverted.

Full height sections

To have full height sections I simply used height to 100vh. It means that the section will take 100% of the Viewport Height whatever the size of the screen is.

🔥 Bonus

To give a better user experience when navigating to your full height sections website you can add this snapping scroll effect on the container of the sections:

scroll-snap-type: y mandatory;

And add this property to tell your section to snap to the scroll of its container:

scroll-snap-align: start;

Everything you need to know about scroll-snap https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-snap-type

✨Final result

Adding a nice font and some color adjustments and we're ready to go!

Wish you liked it! Don't hesitate if you have any questions. Do you have any suggestions about a topic you would like me to cover, it would be a pleasure!

Top comments (0)