By default, the flex items will try to fit in one line. To make items wrap into multiple lines, use:
.parent {
display: flex;
flex-wrap: wrap;
}
Then the items can have flex-basis
.child {
flex-basis: 33.33333 % // For 3 items in a row.
}
Note: Do not use the width
property for the items.
That’s all. 🙏
Explanation:
.parent {
display: flex;
flex-wrap: wrap;
}
The “flex” value for the display property sets the element to a flexible container that can dynamically adjust its items’ sizes and positions. By default, items within a flex container are arranged in a single row, but the “flex-wrap” property allows you to specify whether the items should wrap onto multiple lines or not.
In this case, by setting “flex-wrap” to “wrap”, the items within the “parent” element will wrap onto multiple lines if there is not enough space for them to fit on a single line.
.child {
flex-basis: 33.33333 % // For 3 items in a row.
}
With this code, each “.child” element will take up 33.3333% of the available space along the main axis of the “.parent” element, and if there are more than 3 items, they will wrap onto a new row. You can adjust the percentage value for the flex-basis to control the spacing between items or to create a different number of items per row.
Note that you may need to use additional CSS rules to specify other aspects of the “.child” element’s appearance, such as its height, width, margin, and padding, depending on your design needs.
I also recommend checking CSS Grid – learning by doing! While Flexbox focuses on one dimension either row or column, CSS Grid focuses on a two-dimensional approach – flexible for both columns and rows.
It worked.
to anyone trying this: dont forget to put the “flex-wrap: wrap; ” in the parent CSS property.
didnt work my guy