CSS Flexbox guide // How to center a div in CSS
This is NOT a tutorial on how to learn CSS and requires a brief understanding of it.
❔ What's flexbox?
Sorry in advanced if you're American, I'm from the UK and over here we spell center like centre.
Flexbox is a display type in CSS which can allow you to create awesome looking layouts and answer the age-old question of how do I centre a div?
❔ What can it do?
It can allow easy positioning of child elements and allow cool layouts.
1. Centred div with text in it
2. Evenly spaced, responsive header
3. Image grid (not to be confused with grid layout, credit https://www.w3schools.com/howto/howto_css_image_grid_responsive.asp)
And so much more!
😴 Here for the div centring?
Copy this snippet if you just want to centre a div.:
⭐ Getting started.
Let's explore the basics of flexbox. There are four main flexbox properties. These should all be set on a div as they are best for this type of thing.
You might be wondering...
❔ What are the cross and main axes?
A flexbox is like a container for all of it's child elements (elements inside it) that can apply special positions to them.
The main axis is the axis that is set by flex-flow. It is the way your content flows. For example, if we made a flexbox with
flex-flow: row; or with no flow tag, it will be horizontal. By doing this, we are changing the main axis to horizontal.
The cross axis is the axis that crosses the the main axis, hence the name. This axis is not commonly referred to.
😊 Ok, now I understand it, let's get to some practice!
Now that you understand the concept, we can get to the cool stuff!
First, we'll explore the
justify-content property. It has three main useful options:
space-between. Here is a demo of each:
space-around (My personal favourite):
align-items property is pretty cool, but not as cool as the
justify-content property. It's only really useful when centring things, but it does have a couple of tricks up it's sleeve. It has two main useful options:
flex-end. Please not that this doesn't expand the height of your box and Here are some demonstrations, in which I'm using
This one-liner allows your flexbox to break lines when it runs out of width. Use it if you think that your box will overflow past it's width.
Flexbox will spread elements out as much as possible along the cross axis. Example:
I did not mention everything about flexbox here. I recommend reading up about it on w3schools after you follow this guide.
Want some practice? Try to create these using flexbox!
- Evenly spaced header
- Youtube homepage remake
- Replit-like sidebar