SaaS Developer   
   About    Testimonials    Contact   

A better way to center div or section horizontally and vertically with CSS

Yes, you’ve guessed it - we’ve got a bit of CSS magic this week. :)

Usually, to center a section with CSS you code something like this:

div {
   width: 100px;
   height: 100px;
   position: absolute;
   left: 50%;
   margin-left: -50px;
   top: 50%;
   margin-top: -50px;
}

This week, I found a better way to achieve the same results:

div {
   width: 100px;
   height: 100px;
   position: absolute;
   margin: auto;
   left: 0;
   right: 0;
   top: 0;
   bottom: 0;
}

To center an image, you don’t even need to code its width and height. In this case, the code could be simplified even more:

img {
   position: absolute;
   margin: auto;
   left: 0;
   right: 0;
   top: 0;
   bottom: 0;
}

There’s a couple of benefits I see:

  • It’s pixel-perfect out of the box;
  • No hard coded values for margins leads to easier code maintenance;
  • It could be easily assigned to a separate CSS class to serve a better modularity and minimization of your code.

Let me know your thoughts about this, and good luck with your front-end optimizations!


comments powered by Disqus