Chapter-5 Introduction to Flexbox
Flexbox or flexible box layout module is a layout mode in CSS3 designed to improve the items alignment, direction and order within the container even when items’ size is dynamic (they can be resized or unknown, or should be flexible). So this is a way to say to the webpage: I want that my boxes sit in a line (or a column) with this behavior when the page will shrink or expand.
Prior to Flexbox, web designers were stuck hacking solutions such as floats or tables to get the job done, both of which are often a pain. Now, with Flexbox, they can do this effortlessly:
1. The Two Main Players
To use Flexbox, you need to understand two parts:
- The Flex Container: The parent element (the big box).
- The Flex Items: The children elements (the smaller boxes inside).
To start, you simply apply display: flex; to the parent.
2. The Two Axes
This is the most important concept in Flexbox. Everything moves along two invisible lines:
- Main Axis: Usually horizontal (left to right).
- Cross Axis: Usually vertical (top to bottom).
3. Essential Parent Properties
These are the “commands” you give to the Container to control its children.
justify-content (Aligns items on the Main Axis)
This moves items left, right, or centers them horizontally.
flex-start: Items move to the beginning (default).flex-end: Items move to the end.center: Items are perfectly centered.space-between: Items are pushed to the edges with equal space between them.
align-items (Aligns items on the Cross Axis)
This moves items up or down vertically.
stretch: Items stretch to fill the container (default).center: Items are centered vertically.flex-start/flex-end: Items move to the top or bottom.
flex-direction
This decides if your items should be a row or a column.
row: Horizontal (default).column: Vertical (this swaps the Main and Cross axes!).
4. Essential Child Properties
Sometimes you want one specific “child” box to behave differently than the others.
- flex-grow: Tells a child to take up any leftover space. If you give one item
flex-grow: 1, it will stretch to fill the empty room in the row. - align-self: Allows one specific item to break the rules. Even if the parent says “center everyone,” you can tell one item to go to the bottom (
flex-end).
A Simple Example
If you want to perfectly center a button inside a box, you only need three lines of CSS on the parent:
CSS
.container {
display: flex;
justify-content: center; /* Center horizontally */
align-items: center; /* Center vertically */
height: 100vh; /* Give it some height to see the effect */
}
Why use it?
- No more math: You don’t have to calculate percentages to make things fit.
- Responsive: Items shrink and grow automatically for mobile screens.
- Order: You can change the visual order of items without changing your HTML code.
Check out our resources!
- Bootstrap Templates: Explore our Bootstrap Projects section.
- Free E-Books: Download your Free E-Books here.


