| Updated 28.05.22
Centring in CSS
The fact is as web developers, there are probably a few things that we end up regularly googling to find a quick snippet to copy and paste into our code. We all do it, we can’t be expected to remember everything. I’ve found it quite interesting when having a think about some of the different things that fall into the category of kinda knowing it but needing a refresher every now and then.
One repeated google search for me the longest time was “how to centre X in CSS”, particularly using position and transform to do so. I’m not sure why exactly, but some things just don’t stick in your mind right away even though you use them over and over. What I’ve come to realise is that you need to make a real effort to try to understand what you are using and learn more about it to fully retain the knowledge.
CSS Grid
My new favourite snippet at the moment is using CSS Grid to centre content since it’s only two lines that you add to the container element. It’s so beautifully simple and effective. CSS Tricks has a great resource to use when learning CSS Grid that can be found here. CSS Grid is something I’ve only recently started to reach for over just using flex-box for all my layout problems, I really recommend it.
I have created a little Codepen with some of my favourite ways that I use to centre stuff.
See the Pen
Simple ways to centre | center by Dalton Walsh (@daltonw)
on CodePen.
I didn’t include this common use of flexbox in the pen, but I would bet good money that many devs out there just instinctively write this standard set of centre CSS when working with flexbox. It’s just a habit at this point lol.
Great article, will save for later!