Ensure that flex items are evenly distributed when they wrap around in the layout

I am facing a challenge with my flexbox container where I want it to display elements in multiple rows when there are more than a set number of items. Below is my current approach:

.container {
  display: flex;
  width: 400px;
  background: black;
  padding: 6px;
  margin: 10px;
  flex-wrap: wrap;
}
.box {
  flex: 1 1 0;
  height: 32px;
  flex-grow: 1;
  min-width: 15%;
  border: solid 1px black;
}
.box:nth-child(even) {
  background: blue;
}
.box:nth-child(odd) {
  background: red;
}
<div class="container">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>

<div class="container">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>

<div class="container">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>

Visit this link for the full code snippet.

The issue I'm encountering is that the items in the last row stretch to fill the row unevenly.

My goal is to evenly distribute the elements among rows so that each element is as close to the same size as possible.

For instance, if there are a maximum of 6 elements per row and there are 8 elements total, I want 4 elements on each row instead of 6 on the first row and 2 on the second.

Is achieving this distribution possible using flexbox or any other method?

Answer №1

One clever way to achieve this is by adding a pseudo element to the container with a flex-grow value of around 50. This will effectively create a filler element that occupies the remaining space.

To avoid conflicts, it's important to remove any border rule from the container as it can impact the width calculation and conflict with flex-basis.

Check out the updated example here: https://codepen.io/walidvb/pen/ZXvLYE

Answer №2

To solve the problem, I had to figure out the number of boxes per row on the server side. Then, I used that information to determine the minimum width for each box and applied it using inline CSS.

Update: While it's not ideal, this is currently the only solution available. Unfortunately, CSS alone cannot achieve the desired outcome.

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

Unable to get div elements to expand to their full width

Trying to center items within a div, but having issues achieving the desired output. This is an image of the desired layout: https://i.sstatic.net/949al.png The items in the div are aligning to the left and the input text does not stretch across ...

Effortlessly switch between multiple divs with jQuery

I am working on a functionality where multiple divs should be displayed or hidden based on the button clicked. Initially, all buttons and divs are visible. Upon clicking a button, only the corresponding div should be visible. Subsequent clicks on other but ...

Ensure that the method is passed a negative number -1 instead of the literal number 1 from an HTML error

This is an example of my HTML code: <button (mousedown)="onMouseDown($event, -1)"></button> Here is the TypeScript code for handling the mouse down event: onMouseDown(e: MouseEvent, direction: 1|-1) { this.compute.emit(direction); ...

What is causing the div tag to not align with the top of the body?

Here is my HTML code: <html> <body id="body"> <div id="content"> <div id="head1"> <h3 id="cpsir">CPSIR-CM</h3> </div> </div> </html> This is the CSS code: #body{ background:#0F657D; } #conten ...

I am having trouble getting the color, metalness, lights, and shaders to work properly in Three JS on my

I attempted to create a simple code using Three.js for a red colored torus with a point light and a textured surface, but unfortunately, all I achieved was a black torus that rotates. It seems like the elements in this code are not functioning as expecte ...

Randomly position a div within a grid

I am currently working on creating a grid that spans 100% of the width of the browser window. Firstly, I am unsure about how to approach this grid creation, and secondly, I would like to have a div randomly positioned within the grid, filling the space onl ...

issue with using references to manipulate the DOM of a video element in fullscreen mode

My current objective is to detect when my video tag enters fullscreen mode so I can modify attributes of that specific video ID or reference. Despite trying various methods, I have managed to log the element using my current approach. Earlier attempts with ...

Creating unique CSS class and ID names dynamically in PHP

I have two divs with randomly generated IDs and I would like to use those IDs in my CSS instead of using inline styles. Is there a way to achieve this without creating a separate PHP file with a CSS header? For example, I want the padding for the ID $id_ ...

Are there any known issues with Firefox, jQuery, and CSS animations working in tandem?

As I develop a website with jQuery to manage CSS class switching for animations, I have encountered a strange issue. While Google Chrome and Internet Explorer 9/10 work perfectly, Firefox (Aurora 24 and Firefox 23) does not perform the animations smoothly, ...

React's input onChange event does not trigger for the second time. It only works the first time

Recently, I developed a React JS application to import images from external sources and process them. To handle the user's onChange event, I utilized the onChange attribute to execute my handleChange function. However, I encountered an issue where it ...

Design a table without borders that is compatible for pasting into a Word document

I've been struggling to figure out the correct format for creating a border-less table that, when pasted in Word, will maintain its appearance as shown below: <strong>Foo</strong> <ol> <li value="0">This is zero.</li&g ...

The process of retrieving form parameters when utilizing multipart/form-data in a Spring application

Attempting to retrieve a file using an html form has proven challenging. When utilizing enctype=multipart/form-data, the form parameters and file upload cannot be retrieved. Is there any specific configuration required when using enctype=multipart/form-da ...

Vanishing Div on Window Resize

I am struggling with stacking two columns below a medium screen size using Bootstrap. Currently, only one column stacks while the other disappears (#purple-div). Any suggestions? <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/boo ...

Adjust the window size smoothly to accommodate various height dimensions

Providing Some Background: I am currently developing a Chrome Extension where users have the option to launch it via the default "popup.html", or detach it from the top right corner to use in a separate popup window using window.open. This question also ...

Setting up an event listener for a newly added list through the use of node appendChild

I am currently working on dynamically adding a select list to my HTML document. While I have successfully added the node to the DOM, I am struggling with creating an event listener in a separate JavaScript file that recognizes the newly created select list ...

RShiny encountering issues while trying to load external HTML file along with CSS file

I've been working on a Shiny app, where I put together the UI code using HTML, CSS, and JavaScript within the www sub-folder, while keeping the app.R file in the main folder. The code in my app is structured as follows: runApp( shinyApp( ui = sh ...

Get rid of the right border on the last child pseudo-class

I can't seem to figure this out. It's frustrating because I usually don't struggle with something as basic as a pseudo-class. My goal is to remove the right border of a div element for the last child. I've managed to make it work by ad ...

Give the inner container the ability to expand to fill the remaining space

After formatting my HTML code as shown below: https://i.sstatic.net/oaVVg.png The blue rectangle takes up 70% of the outer container's width, while the green rectangle occupies the remaining 30%. My goal is to have the blue rectangle expand to fill ...

Incorporating both an href link and PHP code using a single click event on a submit button

After exploring various forums, I am still struggling to solve this issue. Can someone please assist me in understanding how to achieve this? When I click the submit button, it currently directs me to a file location via a link without any issues. Howeve ...

Submitting an HTML form to a PHP file for processing before returning to the original HTML page for further interaction

I am looking to figure out how I can send a <FORM> from an HTML page to a PHP file that will retrieve data from a database and then return the results to the same HTML page without any redirection. What I aim for is to avoid redirecting users. Take ...