Mastering CSS Flexbox in 10 Mins
Centering a div used to be the hardest task in web development. Before Flexbox, developers relied on chaotic hacks involving float: left, display: inline-block, and negative margins. It was a nightmare.
Flexbox (Flexible Box Layout) was introduced to solve this exact problem. It provides an ultra-efficient way to lay out, align, and distribute space among items in a container, even when their size is unknown.
The Golden Rule of Flexbox
The most important concept to grasp is the Parent-Child relationship. Flexbox properties are divided into two categories:
- Properties applied to the Parent (the flex container).
- Properties applied to the Children (the flex items inside the container).
To start using Flexbox, you only need one line of CSS applied to the parent container:
.container {
display: flex;
}
Aligning Items: The Main Axes
Once a container is a flexbox, it aligns its children along two axes. The Main Axis (horizontal by default) and the Cross Axis (vertical by default).
Justify Content (Main Axis / Horizontal)
This controls how space is distributed between the items horizontally.
.container {
display: flex;
justify-content: center; /* Centers items horizontally */
/* Other options: flex-start, flex-end, space-between, space-around */
}
Align Items (Cross Axis / Vertical)
This controls how items align vertically inside the container.
.container {
display: flex;
align-items: center; /* Centers items vertically */
/* Other options: flex-start, flex-end, stretch */
}
The Ultimate Hack: Centering a Div
Combining the two properties above gives you the holy grail of CSS: perfectly centering an element horizontally and vertically inside its parent.
.parent {
display: flex;
justify-content: center;
align-items: center;
height: 100vh; /* Make the parent take the full screen height */
}
Building a Responsive Navbar
Flexbox makes building navbars trivial. The space-between property pushes the logo to the far left, and the links to the far right.
.navbar {
display: flex;
justify-content: space-between;
align-items: center;
padding: 0 20px;
}
Flex-Direction
By default, Flexbox lines items up in a row (left to right). If you want them stacked on top of each other (like on a mobile phone screen), you change the direction to column: flex-direction: column;. Note that doing this flips the axes: justify-content now aligns vertically, and align-items aligns horizontally!
Mini Task: Flexbox Froggy
- Go to FlexboxFroggy.com.
- It is a free game where you write CSS Flexbox code to move frogs onto lilypads.
- Beat all 24 levels. Once you do, you will officially be a Flexbox master.