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.

Flexbox: Making “x” items per row
Tagged on:     

Sanjeev Aryal

Don't bury your thoughts, put your vision into reality ~ Bob Marley.

2 thoughts on “Flexbox: Making “x” items per row

  • August 24, 2024 at 9:48 am
    Permalink

    It worked.
    to anyone trying this: dont forget to put the “flex-wrap: wrap; ” in the parent CSS property.

    Reply
  • October 18, 2023 at 8:20 pm
    Permalink

    didnt work my guy

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

× WhatsApp