The almighty 'margin: 0 auto' hack

#26

HTML - CSS

July 31, 2019

alt text

Today I'm posting probably the simplest tip I have ever posted here but this is without doubt, of all my tips, the one I use the most! Do you know when you need to center an element horizontally but it gets trickier than what it should be? We'll, just give a specific width to that element ( it can be width px or % ), apply 'margin:0 auto' and the element will be centered!

<body> <div class="box"></div> </body>

I remember that when I learned about this my life just changed! 😂 Hope that, if you didn't know about this, it will be as helpful for you as it was to me.

.box{ background:url('./bg.jpg') no-repeat center center; background-size: cover; border-radius: 4px; width:80%; height:400px; margin:0 auto; }

What about you? Do you use 'margin: 0 auto' a lot ? 🤔✋