Quick Tip: The Simplest Way To Center Elements Vertically And Horizontally

  • You are here: Free PHP » PHP Tutorials » Quick Tip: The Simplest Way To Center Elements Vertically And Horizontally
the-simple-way-to-center

Flexbox is a relatively new addition to the CSS world and we keep finding more and more excellent applications for it. We can even solve the age-old problem with centering an element both vertically and horizontally with CSS. It is easier than you can imagine – it is only three lines of code, doesn’t require you to specify the size of the centered element and is responsive-friendly!

This technique works in all modern browsers – IE10+, Chrome, Firefox and Safari (with the -webkit- prefix). See the full compatibility table here.

(Play with our code editor on Tutorialzine.com)

The HTML

The idea, of course, revolves around flexbox. First, we create a container in which we want everything to be centered:

<div class="container">
    <!--// Any content in here will be centered.-->
    <img src="fireworks.jpg" alt="fireworks">
</div>

You can place this container div anywhere you want. In the live example above we’ve made it take up the whole width and height of the page.

The CSS

As we said earlier, we will be using only three lines of code. Here they are:

.container{
    display: flex;
    justify-content: center;
    align-items: center;
}

Every flex container has two axis for positioning elements. The main axis is declared with the flex-direction property (can be row or column, see docs). By omitting this rule, we’ve left the flex direction to its default row value.

Now all that we need to do is center both axis. It couldn’t get any simpler:

  1. Make the display type flex, so that we activate flexbox mode.
  2. justify-content defines where flex items will align according to the main axis (horizontally in our case).
  3. align-items does the same with the axis perpendicular to the main one (vertically in our case).

Now that we have set the rules for the vertical and the horizontal alignment to center, any element we add inside the container will be positioned perfectly in the middle. We don’t need to know its dimensions beforehand, the browser will do all the hard work!

Conclusion

There are lots of other techniques for centering content with CSS, but flexbox makes this a whole lot simpler and more elegant. If you wish to learn more about it, check out these resources:

  • A complete guide to flexbox – here.
  • MDN: Using CSS flexible boxes (a long read) – here.
  • Flexbox in 5 minutes – here.
Powered by Gewgley