Flexboxes, Align and Justify Props, Explained
A Full stack Developer who always wonder how things work
As a beginner
, you’ll often find it difficult to understand the differences between “justify-content”, “align-items”, and “align-self”, here’s a quick break down on how to understand these properties and never get confused. This article assumes you have basic knowledge of CSS
classes, selectors, and flex.
Remember the word “Justify”?, Justify positions elements across the horizontal axis, regardless of what follows next, be it “items” “content” or “self”, more on that later. Take a look at the image below and notice the horizontal and vertical axis, this is going to be our container in all examples.
“Align” position elements across the vertical axis regardless of what follows. Here’s the breakdown. Take a look at the image below
The image above does not have any justify or align property set to it, Let’s apply the justify property to the flex-container and see what happens.
Now the flex-items are positioned to the center horizontally but they are not in the center vertically, to position them to the center vertically, we’ll use the align property as shown below
The flex-items are now centered vertically, so what happens when we combine the two?
We achieve a perfect center both vertically and horizontally.
NOTE: When using flex, the default direction is a row, so what happens when a flex-direction: column; is set to a container? Here’s where the confusion lie, The image below shows a typical example of a column direction applied to our initial container.
align-items still work across the vertical axis but because the container is now a column, it appears as if it is working across the horizontal axis.
To move the flex-items to the center horizontally, we’ll have to use the “align” property instead of “justify” to achieve this.
We now know how to use “justify-content” and “align-items”.
So what does “align-self” do and how is it used? Let’s add the align-self property to the first flex-item which is the first red box but before that, let’s give the first box a class of “up”, the code
will look like this
Here’s a summary of what we’ve learned so far:
- “justify” — controls an element across the horizontal axis.
- “align” — controls an element across the vertical axis.
- “self” — picks an individual flex-item in the container.
Are we limited to just “center” and “flex-start”? There are a lot of values that can be used with “justify” and “align” they are but not limited to
- flex-start (default)
Special thanks to Roy Ntaate for reviewing this article.
If there’s any correction or I missed something, please feel free to reach out to me as I am always learning.
Subscribe to get your daily round-up of top tech stories!