One of the strongest features of Flexbox is its ability to handle responsive design with minimal code. By combining flex-wrap and media queries, you can transform a page layout as the screen size changes.
Typically, a navigation menu should look like a horizontal bar on desktop computers and a vertical list on mobile phones.
.container {
display: flex;
flex-wrap: wrap; /* Allows items to drop down */
}
.item {
flex: 25%; /* 4 columns on desktop */
}
/* For mobile phones (tablet/mobile breakpoint) */
@media screen and (max-width: 600px) {
.item {
flex: 100%; /* Switch to 1 column */
}
}
Flexbox allows items to shrink or grow as needed. Setting flex-wrap: wrap is essential to prevent items from becoming too skinny.
.row {
display: flex;
flex-wrap: wrap;
padding: 0 4px;
}
.column {
flex: 25%; /* 4 items per row */
max-width: 25%;
padding: 10px;
}
@media screen and (max-width: 800px) {
.column { flex: 50%; max-width: 50%; } /* 2 per row */
}
@media screen and (max-width: 600px) {
.column { flex: 100%; max-width: 100%; } /* 1 per row */
}
flex-direction: column inside a media query to stack items vertically instead of changing their width.