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:
This week, I found a better way to achieve the same results:
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:
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!