A Beginner's Guide to CSS Flexbox
For years, creating complex layouts on the web required clumsy hacks with floats and positioning. Thankfully, those days are over. CSS Flexbox is a modern, powerful layout module that gives you complete control over the alignment, direction, and order of elements in a container. This guide will introduce you to the core concepts you need to know.
The Two Core Concepts: Container and Items
The Foundation: Flexbox works by defining a flex container and the flex items inside it. You "turn on" Flexbox by setting an element's display property.
The Code: All you need to start is display: flex; on a parent element.
Base HTML Structure:
1
2
3
Activating Flexbox with CSS:
.flex-container {
display: flex;
background-color: #e0e0e0;
}
.item {
background-color: #4f46e5;
color: white;
padding: 20px;
margin: 10px;
}
Try it Yourself: Paste the full HTML and CSS into the HTML Viewer. Notice how the items immediately align in a row. This is the default behavior of Flexbox.
Controlling the Main Axis: justify-content
The Concept: The justify-content property controls how flex items are
distributed along the main axis (horizontally, in a row).
The Solution: You can align items to the start, center, or end, or you can distribute the space between them.
Example CSS Rules:
/* Aligns items to the beginning of the container */
.flex-container { justify-content: flex-start; }
/* Aligns items to the center */
.flex-container { justify-content: center; }
/* Distributes space evenly between items */
.flex-container { justify-content: space-between; }
Try it Yourself: In the live editor, change the value of
justify-content to center, flex-end,
space-around, and space-between to see how the layout instantly
changes.
Controlling the Cross Axis: align-items
The Concept: The _align-items_ property controls how flex items are aligned along the cross axis (vertically, in a row).
The Solution: This property allows you to vertically center items, stretch them to fill the container, or align them to the top or bottom.
Example CSS Rules:
/* (Assumes the container has a set height, e.g., height: 200px) */
/* Stretches items to fill the container's height (default) */
.flex-container { align-items: stretch; }
/* Aligns items to the vertical center */
.flex-container { align-items: center; }
/* Aligns items to the top */
.flex-container { align-items: flex-start; }
Try it Yourself: Add a height: 200px; to your
.flex-container in the live editor. Now experiment with the different
align-items values to see their effect.
Allowing Items to Wrap: flex-wrap
The Problem: By default, flex items will try to fit onto one line, even if it means overflowing their container. This is bad for responsive design.