Before turning them into Flexbox layouts, the elements will be stacked as follows:
I created a little style for it, but that doesn't affect Flexbox.
To turn it into a Flexbox layout, we just need to supply the following CSS attribute container:
.container {
display: flex;
}
This will automatically sort items according to the horizontal axis.
If you want to check the actual code, you can access the Scrimba playground (https://scrimba.com/c/c3zpnuB).
Now rearrange these items a bit.
Justify-content and align-item are two CSS properties that help us distribute items in the container. They control how items are positioned along the main axis and cross axis .
In this case (not always), the horizontal main axis and vertical cross axis:
In this article, we only look at justify-content
, as I see it being used more than align-items
. However, in the upcoming course, I will pass both specific properties.
Focus all the items along the main axis using justify-content
:
.container {
display: flex;
justify-content: center;
}
Or maybe set it to space-between
, there will be more space between items like:
.container {
display: flex;
justify-content: space-between;
}
Here are the values you can set for justify-content:
You should learn about these values and see how they show up on the page. That will help you understand the concept correctly.
We can control individual items. Suppose we want to keep the first two items on the left and move the logout
button to the right.
To do this, we will use the old technique to set the auto
margin.
.logout {
margin-left: auto;
}
If you want both the search
and logout
items to be pushed to the right, simply add margin-left
instead of the search
entry.
.search {
margin-left: auto;
}
It will push the search
item to the right, again you will push the logout
item as shown:
Up to now, we have only fixed-width
entries. But what if we want to display responsive? To do this, we need to have an attribute called flex
. This makes it much easier than the old way of using percentages.
Simply aim all the items and give them a flex
value of 1
.
.container > div {
flex: 1;
}
As you can see, it extends the items to fill the entire container.
In many cases, you may want to select one of the items to open more widths and therefore, only put one if they have flexible width. For example, we can make the search
item have more space:
.search {
flex: 1;
}
Before the end of the article, I want to tell you that flex properties are an abbreviated feature from three attributes: flex-grow , flex-shrink and flex-basis .
Author: Per Harald Borgen
Refer to some more articles:
Having fun!