Ensure that each row contains no more than 5 items, and use flexbox to automatically resize

I currently have the following setup:

.container {
  background: gray;
  width: 600px;
  display: flex;
  flex-flow: row wrap;
  position: relative;
}
.item {
  background: blue;
  width: auto;
  height: auto;
  margin: 4px;
  flex: 1;
  flex-basis: 20%;
}
<div class="container">
  <div class="item">A</div>
  <div class="item">B</div>
  <div class="item">C</div>
  <div class="item">D</div>
  <div class="item">E</div>
  <div class="item">F</div>
  <div class="item">G</div>
</div>

I want to display 5 items per row in a flexbox, but they are not appearing because their width/height is not set. How can I automatically resize the items so that 5 of them fit on each row?

Any suggestions on how I can achieve this?

Thank you!

Answer №1

You are correct by specifying a flex-basis: 20%, but it's important to account for the 4px margin on each flex item in order for it to wrap properly.


Ensuring Equal Width Flex items in the Last Row

To achieve this, use flex: 0 1 calc(20% - 8px) - which ensures the item won't exceed 20% of width (adjusted for margin) and can shrink based on the container width. See the demonstration below:

.container {
  background: gray;
  width: 600px;
  height: 200px; /* height specified for illustration purposes */
  display: flex;
  flex-flow: row wrap;
  position: relative;
}

.item {
  background: blue;
  margin: 4px;
  flex: 0 1 calc(20% - 8px); /* <-- adjustment for margin */
}
<div class="container">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div>


Another alternative involves setting flex-grow to one and using flex-basis: calc(20% - 4px) with flex: 1 1 calc(20% - 4px), paired with a pseudo-element that fills the remaining space:

.container {
  background: gray;
  width: 600px;
  height: 200px; /* height specified for illustration purposes */
  display: flex;
  flex-flow: row wrap;
  position: relative;
}

.item {
  background: blue;
  margin: 4px;
  flex: 1 1 calc(20% - 8px); /* <-- adjustment for margin */
}

.container:after {
  content: '';
  display: block;
  flex: 999; /* large growth factor */
}
<div class="container">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div>

If you do not have the requirement of having a specific number of items per row, you may find this useful:

  • Unordered list that acts like grid-auto-flow dense

Expanding Flex Items in the Last Row to Fill Available Space

In scenarios where there are fewer than 5 items in a row and you want them to occupy the available space, utilize flex: 1 1 calc(20% - 8px) where flex-grow is set to 1 allowing the flex items in the last rows to expand and fill the remaining space:

.container {
  background: gray;
  width: 600px;
  height: 200px;  /* height specified for illustration purposes */
  display: flex;
  flex-flow: row wrap;
  position: relative;
}

.item {
  background: blue;
  margin: 4px;
  flex: 1 1 calc(20% - 8px);  /* <-- adjustment for margin */
}
<div class="container">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div>

Answer №2

Here is a CSS snippet to arrange five items in each row:

.container {
  background: gray none repeat scroll 0 0;
  display: flex;
  flex-flow: row wrap;
  position: relative;
  width: auto;
}

.item {
  background: blue none repeat scroll 0 0;
  flex: 1 1 18%;
  height: auto;
  margin: 4px;
  padding: 20px 0;
  width: auto;
}
<div class="container">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div>

Answer №3

In my current WordPress project, I needed to organize articles by categories and display them in columns that adjust based on the browser width. To achieve this responsive layout, I wrote some custom CSS code.

.container {
  margin: 20px auto;
  width: 80%;
  min-height: 100px;
  display: flex;
  flex-flow: row wrap;
}

.item {
  margin: 10px;
  flex: 1 1 calc(20% - 20px);
  background-color: lightgreen;
}

@media screen and (max-width: 1200px) {
  .item {
    flex: 1 1 calc(25% - 20px)
  }
}

@media screen and (max-width: 900px) {
  .item {
    flex: 1 1 calc(33% - 20px)
  }
}

@media screen and (max-width: 750px) {
  .item {
    flex: 1 1 calc(50% - 20px)
  }
}

@media screen and (max-width: 550px) {
  .item {
    flex: 1 1 calc(100% - 20px)
  }
}
<div class="container">
  <div class="item"><a>Link1</a></div>
  <div class="item"><a>Link1</a></br><a>Link2</a></div>
  <div class="item"><a>Link1</a></br><a>Link2</a></br><a>Link3</a></div>
  <div class="item"><a>Link1</a></br><a>Link2</a></br><a>Link3</a></br><a>Link4</a></div>
  <div class="item"><a>Link1</a></br><a>Link2</a></br><a>Link3</a></br><a>Link4</a></br><a>Link5</a></div>
  <div class="item"><a>Link1</a></br><a>Link2</a></br><a>Link3</a></br><a>Link4</a></br><a>Link5</a></br><a>Link6</a></div>
</div>

Answer №4

Check out this potential fix: https://jsfiddle.net/9f955jk2/3/ It's important to consider margins and paddings, which is why I adjusted the width to 18%. If you remove all margins and paddings, you could set it to 20% (100%/5 items per row). Remember that borders also add space. The container should be set to 100%, or else divide the width by 5 and specify in pixels for each item instead of percentages.

.container {
      width: 100%;
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is causing columns.render not to trigger when DataTable().draw() is invoked?

I'm wondering why the columns.render method is not part of the execution flow when using DataTable().draw(). For instance: HTML <table id="data"> <thead> <tr> <th>TimeColumn</th> < ...

CompletePage script, individual automatic scrolling

Having trouble with my fullPage.js implementation. I have a total of 5 sections and I'm trying to set different scrolling behaviors for each section. Specifically, I want Sections 1 through 3 to auto-scroll and Section 4.1 to 4.2 to use normal scroll. ...

Looking to transform a list into JSON format using JavaScript?

I have a collection that looks like this: <ol class="BasketballPlayers"> <li id="1">Player: LeBron, TotalPoints: 28753, MVP: true</li> <li id="2">Player: Steph, TotalPoints: 17670, MVP: true< ...

Due to the feature in VISUAL STUDIO CODE that presents folders and subfolders at the same level

While working on my Angular project, I encountered an issue with creating a subfolder within a folder. Despite trying the same process in Windows Explorer, I faced the same problem of them appearing on the same level. What could be causing this discrepan ...

Scaling the ion-spinner to fit your specific needs

In my Ionic application, I am utilizing the ion-spinner. However, I have encountered an issue with resizing the spinner. While custom CSS works well with default spinners, it does not function properly with Bubbles, Circles, and Dots spinners. CSS .spin ...

Is there a way to develop a login form that retrieves information from a Google Sheet database?

Please help me with a solution. I have developed a registration form which effectively saves users' information in a Google Sheet. However, now I am yearning to create a login form that verifies the stored data and redirects the user to a different pa ...

The {shade} of the code has been modified within brackets

Ever encountered your code's colors abruptly changing to red and green in the middle of an HTML page? My editor is Brackets, and while it doesn't pose any issues, it's really bothersome and makes the code difficult to read: Take a look at t ...

Fixed headers remain in place as you scroll horizontally on a single table

Within my system, I have organized two tables: table one and table 2 are stacked on top of each other. I've managed to freeze the column headers so that they are displayed vertically, remaining static as users scroll horizontally. To achieve this effe ...

Encountering an error while trying to execute `$(document).ready(function() {}

Recently, I delved into the world of JavaScript, particularly Jquery. As I encountered the $(document).ready(function() {}); statement and added it to my code, I faced an issue when placing it within the header tag of my HTML. The script tag would display ...

Designing GWT FlexTable using pure CSS styling

Is there a way to style a GWT FlexTable using CSS alone? The API doesn't provide information on available CSS classes. Are there no predefined classes and do I need to define them myself? I am particularly interested in styling the "th" element. ...

How wide should the website layout be?

What is the perfect size for a standard portal website? I've seen many sites with widths ranging from 960px to 1000px. ...

Javascript callback function cannot access variables from its parent function

As a Javascript newbie, I am currently diving into callbacks for my project. The goal is to retrieve address input from multiple text boxes on the HTML side and then execute core functionalities upon button click. There are N text boxes, each containing an ...

Issue with Trix text editor not triggering the change event

Lately, I've been facing some difficulties in getting the tirx-change event to trigger when there are changes in the content of a trix-editor. Despite using React JS for the view, I haven't been able to identify the problem. Below is the code sni ...

Is there a way to specifically dictate the order in which flexbox items expand or contract?

I am facing an issue with my flex container setup involving three children elements. I have specified both minimum and maximum widths for each child, but I want them to grow or shrink in a specific order as the window width changes. Ideally, Item1 should s ...

Excessive white space at the bottom of a floated image within a small parent element

I need help with styling a page that will only be viewed on mobile Safari. The HTML markup is as follows: <blockquote> <p><img src="..."/> A paragraph...</p> <p>...</p> ... </blockquote> Here is the CSS u ...

Enhancing URLs with jQuery/AJAX: A Comprehensive Guide to Adding Parameters

Whenever I try to use the get method on an HTML form, the submitted data automatically appears in the URL. You can see what I mean here. Interestingly, when attempting to achieve the same result with JQuery and AJAX using the get method, the data doesn&apo ...

Uploading images in PHP

I need assistance with uploading an image to a server using PHP, saving it inside a directory, and then retrieving the image URL. Here is my HTML code: <form method="post> <fieldset> <div class="form-group col-md-6 col-lg-6 col-sm-1 ...

Tips for creating a static PHP website with a fixed navigation bar and footer

I am looking to create a webpage with a consistent horizontal navigation bar and footer, but where the content changes dynamically based on the user's interactions with the navigation. For example: <div class="nav-bar"> /* The navigation bar r ...

Using the .slider class on concealed div elements

Explaining this may be a bit tricky, but here we go... I have multiple hidden divs that switch with each other when a link is clicked using $(document).ready(function(){ $('a').click(function () { var divname= this.name; $("#"+divname ...

Transforming the playbackRate property of a web audio-enabled audio element

I recently experimented with integrating an audio element into the web audio API using createMediaElementSource and achieved success. However, I encountered an issue when attempting to change the playback rate of the audio tag. Despite trying multiple appr ...