Display and Flexbox Basics
Putting things side by side, finally
So far, everything on your page stacks vertically: one element, then the next below it, all the way down. That is fine for an article, but real websites put things side by side: a logo next to a menu, buttons in a row, cards in a line. This lesson is where your layouts come alive.
Block and inline
First, a little background. Every element has a default display behavior. Block elements, like <p>, <h1>, and <div>, take up the full width available and always start on a new line. That is why everything stacks. Inline elements, like <a> and <strong>, flow along inside a line of text instead. The display property lets you change this behavior, and its most useful value, by far, is flex.
Meet flexbox
Flexbox is a layout system built into CSS. The idea: you pick a container element, turn it into a flex container, and its children line up in a row automatically.
<div class="toolbar">
<button>Save</button>
<button>Share</button>
<button>Delete</button>
</div>
.toolbar {
display: flex;
gap: 8px;
}
Two lines of CSS and the buttons sit in a neat row with 8px between each one. The gap property is a gift: it adds space between the items only, with no awkward extra space at the ends.
Here is the rule to tattoo on your brain: flex properties go on the parent, not the children. You style the container, and the items inside arrange themselves. Forgetting this is the number one flexbox confusion, so check it first whenever flexbox seems broken.
Controlling the row
Two properties control where items sit inside the container:
justify-contentpositions items along the row:flex-start(default),center,flex-end, orspace-between, which pushes the first item to one end and the last to the other.align-itemspositions items across the row, vertically in a normal row:centeris the one you will use most, to vertically center items of different heights.
Here is the classic website header, with the site name on the left and navigation links on the right:
.site-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 16px;
}
That is the exact pattern used by an enormous number of real websites. You now know how it works.
The centering trick everyone loves
For years, perfectly centering something in CSS was famously painful. Flexbox ended that. To center a child both horizontally and vertically inside a container:
.hero {
display: flex;
justify-content: center;
align-items: center;
height: 300px;
}
Play with this on your site: wrap your navigation links in a container, set display: flex; and gap: 16px; on it, and watch your vertical list of links become a proper menu bar.
Quick check
Q1 You want three cards to sit in a row. Where does display: flex; go?
Q2 What does the gap property do in a flex container?
Want to save your progress? It's free.
Create a free account