Understanding how flex-wrap property works in flexbox is essential for creating

Take a look at the code snippet below:

.flex-container {
  padding: 20px;
  margin: 20px;
  list-style: none;
  border: 1px solid silver;
  -ms-box-orient: horizontal;
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -moz-flex;
  display: -webkit-flex;
  display: flex;
  justify-content: space-evenly;
}

.wrap    { 
  -webkit-flex-wrap: wrap;
  flex-wrap: wrap;
}  
.wrap li {
  background: gold;
}

.flex-item {
  border: 1px solid blue;
  background: tomato;
  padding: 5px;
  width: 100px;
  height: 100px;
  margin: 10px;
  
  line-height: 100px;
  color: white;
  font-weight: bold;
  font-size: 2em;
  text-align: center;
}
<ul class="flex-container wrap">
  <li class="flex-item">1</li>
  <li class="flex-item">2</li>
  <li class="flex-item">3</li>
  <li class="flex-item">4</li>
  <li class="flex-item">5</li>
  <li class="flex-item">6</li>
  <li class="flex-item">7</li>
  <li class="flex-item">8</li>
  <li class="flex-item">9</li>
</ul>

I'm looking for some help: Is there a way to use flexbox to ensure that only three boxes are displayed in one row while maintaining their original widths? I want to evenly distribute the remaining space, accommodating a total of nine boxes in three rows with three boxes each. How can this layout be achieved using flexbox?

Answer №1

If you're looking for solutions to a layout problem, there are various hackish approaches available. You can find some suggestions here. Unfortunately, the cleanest solution using flexbox seems to only be supported by Firefox.

Instead of relying on hacks, I recommend utilizing CSS Grid for your needs. A great resource for learning CSS Grid is available here.

.grid-container {
  display: grid;
  grid-gap: 20px;
  grid-template-columns: repeat(3, 1fr);
  justify-items: center;

  padding: 20px;
  list-style: none;
  border: 1px solid silver;
}

.grid-container li {
  background: gold;
}

.grid-item {
  border: 1px solid blue;
  background: tomato;
  padding: 5px;
  width: 100px;
  height: 100px;
  
  line-height: 100px;
  color: white;
  font-weight: bold;
  font-size: 2em;
  text-align: center;
}
<ul class="grid-container">
  <li class="grid-item">1</li>
  <li class="grid-item">2</li>
  <li class="grid-item">3</li>
  <li class="grid-item">4</li>
  <li class="grid-item">5</li>
  <li class="grid-item">6</li>
  <li class="grid-item">7</li>
  <li class="grid-item">8</li>
  <li class="grid-item">9</li>
</ul>

Unlike many other techniques, CSS Grid has excellent browser support. To verify its compatibility with different browsers, you can refer to this link: here.

Answer №2

Implement flex-basis: 33% as it is universally supported by all browsers, then utilize the calc method to eliminate the margin and padding between the boxes.

Review my code:

.flex-container {
  padding: 20px;
  margin: 20px;
  list-style: none;
  border: 1px solid silver;
  -ms-box-orient: horizontal;
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -moz-flex;
  display: -webkit-flex;
  display: flex;
  justify-content: space-evenly;
}

.wrap {
  -webkit-flex-wrap: wrap;
  flex-wrap: wrap;
}

.wrap li {
  background: gold;
}

.flex-item {
  border: 1px solid blue;
  background: tomato;
  padding: 5px;
  width: 100px;
  height: 100px;
  margin: 10px;
  line-height: 100px;
  color: white;
  font-weight: bold;
  font-size: 2em;
  text-align: center;
  flex-basis: calc(33.3% - 32px);
}
<ul class="flex-container wrap">
  <li class="flex-item">1</li>
  <li class="flex-item">2</li>
  <li class="flex-item">3</li>
  <li class="flex-item">4</li>
  <li class="flex-item">5</li>
  <li class="flex-item">6</li>
  <li class="flex-item">7</li>
  <li class="flex-item">8</li>
  <li class="flex-item">9</li>
</ul>

Answer №3

To ensure that the boxes are fixed to 100px, you can implement the following CSS:

.container { 
  flex-wrap: wrap;
  width: calc(120px * 3 + 40px); 
}

Meaning,

width multiplied by number of boxes plus container padding

This method will consistently wrap the boxes as desired - although it's not a typical flex box solution, it should suffice for your specific situation.

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

Find all Mondays occurring within a specified date range using Moment.js

I need to extract all Mondays within a specific date range. let start = moment(this.absence.FromDate); let end = moment(this.absence.ToDate); The user has the option to deactivate certain weekdays during this period by setting booleans. monday = true; t ...

Traversing an array of objects using D3.js

I'm attempting to create a row of bars that are all the same height and width based on their titles. I have an array of 100 objects, each with a key called results containing another array of 20 objects. This means I should end up with a row of 2000 b ...

Link Quick Techniques

I currently have an Express server set up with CRUD methods My goal is to automatically trigger the get method whenever a post, put, or delete request is made. This will ensure that the view on the Front-end side gets updated accordingly. Below is an exc ...

Encountering a CORS issue when utilizing Stripe with various servers while navigating with a Router

I have a router that utilizes Router.express(). The backend operates on port 5000, while the frontend runs on port 3000. Within the frontend folder, there is a button with a fetch request (http://localhost:5000/create-checkout-session). In the backend, the ...

Deleting Empty Session Data

I have set up sessions for my website. In order to initialize the session, I included the following code on every link of the website: session_start(); if(isset($_SESSION['User'])) { //session_start(); $sesvar = $_REQUEST['sid']; } ...

Getting a specific value from a REST API array in JavaScript: Tips and tricks

After being stuck on this problem for 8 hours, I finally decided to seek help: In my JavaScript file, I am attempting to extract data from a REST API response. The response consists of an array of objects structured like this: [{"start":"2017-04-21 14:40 ...

Import several image files using AngularJS

I recently came across a helpful tutorial that demonstrates how to upload pictures from your local computer using AngularJS directives. As a newcomer to Angular, I followed the instructions but now I'm stuck on modifying it to display the selected ima ...

Node JS GET request using fetch stops displaying console outputs after a certain duration

I am currently working on building a calendar application using node, mongodb, html, css, and javascript. The main goal is to allow users to input dates as events which can be displayed dynamically. I am facing an issue where, upon trying to retrieve these ...

Vue.js - Resetting child components upon array re-indexing

I am working with an array of objects const array = [ { id: uniqueId, childs: [ { id: uniqueId } ] }, { id: uniqueId, childs: [ { id: uniqueId } ] }, ] and I have a looping structure ...

What could be causing issues with angularjs ng-include not functioning properly in Chrome at times?

<html ng-app="myApp1"> <head> <title>NG-Include</title> <script src="angular.js"></script> <script src="filter.js"></script> </head> <body> <div ng-controller="myController"> ...

The image is exceeding the boundaries of its parent element, even though a height has been specified

I need assistance with aligning an image inside a div that should take the height of its parent div, specifically the .hero class. Despite setting the image's height to 100%, it still extends beyond the parent div and doesn't adhere to the specif ...

Despite utilizing the .img-fluid class, the image remains incompatible with the parent div and does not fit properly

So, I'm currently working on a test code where my aim is to fit an image into the parent div using Bootstrap 5. However, I'm facing a challenge where the image leaves a noticeable gap width-wise, despite using the .img-fluid class. You can see th ...

Attempting to extract the data from SweetAlert

I've been attempting to retrieve the return value from sweetalert, but I encountered this: Promise {<pending>} >__proto_:Promise [[PromiseStatus]]: "resolved" [[PromiseValue]]:true resulting from this piece of code: var ret = swal({ ...

Revoking existing Json Web Tokens when updating user information

Once a user logs in with their username and password, they receive an access_token containing the payload that includes their uniqueTokenIdentifier. This unique identifier is stored for each user in the database. If a user changes their password due to ac ...

Fixing the error message "page attempting to load scripts from an unauthenticated source"

Can you help me troubleshoot an issue on my PHP page with ad scripts? I recently switched my site from HTTP to HTTPS and now the scripts are not appearing. Here is the error I found in the dev console: Failed to load resource: the server responded with ...

Steps for replacing the firestore document ID with user UID in a document:

I've been attempting to retrieve the user UID instead of using the automatically generated document ID in Firebase/Firestore, but I'm encountering this error: TypeError: firebase.auth(...).currentUser is null This is the content of my index.js ...

Retrieve a file through a POST request with node.js

Hi everyone, I'm trying to create a "export to excel" functionality in Node.js for a page. By using Chrome DevTools, I discovered that the file is downloaded after a post request, so I need to replicate it. https://i.sstatic.net/aL9SO.png var reques ...

Guide to fetching and displaying a complex array API using JavaScript's fetch method

Recently, I've been delving into the world of APIs and making sure I call them correctly. Using the fetch method has been my go-to so far, and here's a snippet of the code where I reference an API: fetch('https://datausa.io/api/data?d ...

There was a parsing error due to an unexpected token, and we were expecting a comma instead

Below is the code snippet written in react js: class Posts extends Component { render() { return ( {console.log('test')} ); } } When I executed this code, an error occurred stating: Parsing error: Unexpected token, expected " ...

The ReactJS Ajax request returns a successful status code of 200 and retrieves the data, however, an error message

I have the following code snippet to fetch data from a backend API. When I paste the link into my browser's address bar, the API returns a result of '["2016-03-31T00:00:00"]'. However, when I use this AJAX call in my code, I receive a status ...