You may have seen this question, center a div, or whatever, in interviews or other places. I am sure there are other approaches than I am sharing here, but I found these two cool ideas from multiple places (see refs at the end). These are not my original ideas so I will be sure to share where I learned these from:
Using display:flex
Make sure you know how flex works, but to do centering with flex, it's ridiculously simple:
Now everything inside <div class="container"> </div> will be centered in both directions!
Using display:grid
You are so going to thank for me this one, you are welcome. This one is so simple it does not even need an explanation does it?
Try it out in CodePen, Codesandbox or whatever tool you use to do your CSS/JS stuff!
Where I learned these from:
[1] A wonderful compilation of one liner CSS tricks! https://web.dev/one-line-layouts/
[2] The wonderful book CSS in Depth By Keith J. Grant. It's wonderful to read CSS from a book, for a change.
Comments
Post a Comment