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

Merging columns in Bootstrap 4 grid system

I have been working on creating a Bootstrap grid with the following structure: .facevalue { background: #ffffff61; font-family: Dubai; font-size: 18px; font-weight: 400; line-height: 30px; padding: 0 30px; border: 1px solid #e9e9e9; ma ...

The Viadeo Social Toolbox seems to be encountering technical difficulties at the moment

I attempted to utilize a Viadeo Social Toolbox, specifically the Viadeo Share Button, but it seems to be malfunctioning in certain browsers? I came across some outdated viadeo share URLs like this: http://www.viadeo.com/shareit/share/?url=${url}&title ...

Launching an image link within the same location on the subsequent page to which it is directed

I'm completely new to creating websites so I may not be using the correct terminology. I've searched with various terms and ideas but haven't found any solutions to help me ask my question effectively or find examples of what I'm lookin ...

Getting to grips with accessing HTML elements within a form

<form name="vesselForm" novalidate> <input type="text" id="owner" name="ownerEdit" required ng-blur="vesselForm.btnCC.attr('value', 'Change Customer')"/> <input type="button" name="btnCC" value="Customer" /> </fo ...

On a medium-sized screen, a collapsible button unexpectedly appears amidst the various links

Can anyone help me with sorting out the order of navbar elements? I'm facing an issue where on small screens, the collapse button appears above the links, but on medium screens, it shows up before the last link in the menu. Any suggestions on how to f ...

The appropriate use of spacing after text in the context of HTML and

Why is it that when I add padding or margin, no extra space is created after the text? Here is the output: I have tried adding padding and margin after the Stay Tuned text, but it seems to be not working. Any insights on what might be causing this issue? ...

I encountered an error message that said: "Cannot assign '12': 'Cart.product' must be a 'Product' instance. Can someone please assist me in resolving this problem?"

[Included in the image of my code is the add-to-cart function where the error can be found on line 5] def add_to_cart(request): user = request.user product_id = request.GET.get('prod_id') product = Product.objects.get(id=product_id) ...

Setting the width of colspan elements can be challenging when other columns have dynamic widths

I am working with a table setup that includes various columns for data tracking: <table > <thead style="width: calc(100% - 15px); display: table; table-layout: fixed;"> <tr> <th colspan="3">& ...

What is the best way to ensure text starts on a new line when paragraphs and images are floating and aligned?

Does anyone have a clearer title idea? Feel free to edit. To better illustrate my point, I've created a jsfiddle. I am working with a simple layout of text and images. My goal is to make the second text and image appear on a new row just below the f ...

What is the best way to finish up the JavaScript code below?

Having just started learning JavaScript, I am struggling to figure out how to use JavaScript to clear the text in a text box and move it below the box when a user starts typing. I've been watching this tutorial http://codepen.io/ehermanson/pen/KwKWEv ...

React and Material UI: Ensuring Proper Whitespace Handling in Strings

Exploring the use of Typography component from Material UI (https://material-ui.com/api/typography/) The main objective is to maintain the new lines and spaces in a saved string. For instance, if the string contains leading spaces and new lines, it shoul ...

Dynamic binding of CSS properties in AngularJS is a powerful feature that enables

I am attempting to dynamically bind the css property counter-reset in AngularJS. To see my efforts, check out this Fiddle link. Essentially, I aim to have the numbering of li elements begin with the number specified in the controller. Despite trying to us ...

Position the Bootstrap button on the right side

this is the code I am working with: <p class="h1 p-3 mb-2 bg-danger text-white text-danger">Lagerbestand unter Mindestmenge! </p> <br /> <div class="border text-center"> <p class="h5 text-center">Durc ...

Jquery function for determining height across multiple browsers

I am currently facing an issue with setting the height of table cells in my project. While everything works smoothly on most browsers, Firefox seems to add borders to the overall height which is causing inconsistency across different browsers. If anyone k ...

The validation process is still failing even though the correct credentials have been entered

I'm diving into the world of Javascript and DOM today, but I've hit a roadblock. Can you take a look at this code snippet and help me figure out what's causing me to always end up in the else block, no matter what I input in the text field? ...

How come the spacing between my columns decreases as I expand the width of my container?

I'm struggling to grasp the concept behind the column gap in a multi-column layout. Take a look at the HTML/CSS code snippet I have set up in this Fiddle: <div class="flex-container"> <div class="flex-item">1</div& ...

Reveal and conceal information with a customized web address

I have a PHP and MySQL blog that I want to display in a div using show and hide JavaScript functions. Everything works fine with other divs, but the issue arises when clicking on a vanity URL causing my webpage to refresh every time it's clicked. The ...

display data labels within the chart - utilizing the power of angular.js in conjunction with chart.js

My goal is to display the chart's information without requiring the user to hover over any part of the chart. I am utilizing Chart.js with Angular.js I have the same question as this one posted here: question here! html code: <div class="wrapper ...

Determine the outcome of the assessment quiz

Greetings everyone, I apologize for my poor English. I've been searching through numerous documents, but due to my language barrier, I am having trouble understanding them. I have designed a quiz page, but I'm facing an issue where I can't d ...

What's causing the text not to wrap when using float?

I've tried setting float:left for the image and float:right for the text, but the image is still overlapping the text. What I really want is for the text to wrap around the image - to be on the right side of the image at the beginning and below the i ...