At times you may wonder how to make your containers (divs for example) be able to meet your layout needs. Well, there are lots of candidate CSS attributes out there, but one of the best and easiest to use is CSS flex.
CSS flex is just but a CSS display attribute, identified by the keyword flex. That is all you need to do to make your container a flex layout. With that said, sit tight as we dive on how to make a CSS container have a flex behavior.
Well, let’s get straight to the point with this HTML example.
<div class="parent">
Parent
<div class="child">
Child
</div>
</div>
Then on CSS or SCSS, have this setup and define the CSS display like so:
.parent {
display: flex;
.child {
}
}
This is all that it takes to make your parent container a CSS flex layout. Now, you may wonder, how does CSS flex work, well, that is the next topic.
CSS flex layout is one dimensional. This means that it can either work with respect to the row or column of the target element.
In other words, you can think of row as horizontal orientation and column as vertical orientation.
These will be discussed in the section for setting parent orientation. However, now, the next question is how it works or what does it mean for the container to flex (no pun intended)
Well, the name flex means the ability to be malleable and is the direct opposite of straight.
Now, when it comes to CSS flex, it means that the parent element will now have the ability to bend and curve the rules as needed to achieve desired behavior, or as simply put, to set the desired orientation.
So, now that you have an understanding of what CSS flex does to a parent element, the next part is to understand how to set the orientation.
This is where we have flex-direction.
This is the orientation which the parent will need to be envisioned as having. As stated above, it can be vertical or horizontal. So you set it like so:
.parent {
display: flex;
flex-direction: column;
.child {
}
}
The above code will make the parent have a vertical orientation. So it’s child elements will be positioned vertically on top of one another.
The other variant will would be:
.parent {
display: flex;
flex-direction: row;
.child {
}
}
With this option, the parent will have, yes, you guessed it right, a horizontal orientation. That means the child elements will be positioned side by side.
NB: If you don’t specify the direction, the default CSS flex direction is row.
As you can see, it is really simply to make your container elements have CSS flex layout in them.
You can actually make your containers CSS flex responsive, but that is out of the scope of this tutorial, we may cover this later in future.
Well, that is it for now.