CSS Flexbox for WordPress themes: a practical guide
Flexbox is a one-dimensional layout model: it arranges items in a row or in a column, distributes the free space and aligns them. It works in all current browsers and replaces floats and inline-block tricks in navigation bars, rows of cards, centred hero sections and the footer at the bottom of a short page.
Problem: Aligning items in a row, centring something vertically or making cards of equal height takes floats, clearfix hacks and fixed heights.
Solution: Set display: flex on the container, control the main axis with justify-content, the cross axis with align-items, wrapping with flex-wrap, and the size of each item with flex.
The container
.nav-menu {
display: flex;
flex-wrap: wrap; /* allow items to go to the next line */
justify-content: space-between; /* distribute along the row */
align-items: center; /* align vertically */
}
.sidebar {
display: flex;
flex-direction: column; /* a column instead of a row */
}
The items
.card {
flex: 1 1 280px; /* grow, shrink, start from 280px */
}
.card--featured {
flex: 2 1 280px; /* takes twice as much of the free space */
}
/* Push the last menu item (a button) to the right */
.nav-menu .menu-item-cta {
margin-left: auto;
}
/* Centre content in both directions */
.hero {
display: flex;
align-items: center;
justify-content: center;
min-height: 60vh;
}
Items in a row stretch to the height of the tallest one by default (align-items: stretch), so cards of equal height need no extra code.
A grid of posts
The space between the cards is made with margins: a negative margin on the container compensates for the margins of the outer cards.
.posts-grid {
display: flex;
flex-wrap: wrap;
margin: 0 -0.75rem;
}
.posts-grid .post-card {
flex: 0 0 calc(33.333% - 1.5rem);
margin: 0 0.75rem 1.5rem;
}
@media (max-width: 900px) {
.posts-grid .post-card { flex-basis: calc(50% - 1.5rem); }
}
@media (max-width: 600px) {
.posts-grid .post-card { flex-basis: calc(100% - 1.5rem); }
}
The footer at the bottom
On short pages the footer moves up into the middle of the screen. A column flexbox on the page wrapper keeps it at the bottom:
.site {
display: flex;
flex-direction: column;
min-height: 100vh;
}
.site-content {
flex: 1 0 auto; /* takes all the free height */
}
Update (2021): The gap property now works for flexbox in all major browsers (Chrome 84, Firefox 63, Safari 14.1), so the negative-margin trick can be replaced with gap: 1.5rem on the container.
NOTE: Flexbox is for one direction. When you need rows and columns aligned at the same time, as in a page layout, CSS Grid is the better tool.