Arrange divs in a grid layout with evenly distributed dynamic spacing

I am not a big fan of bootstrap, so I was wondering if it is possible to achieve the layout without using it.

I have 6 divs that I want to arrange in 2 rows and 3 columns. I need the space between each row/column to be precise. While I can calculate this manually, I am curious if there is a better solution available.

Keep in mind that the height of .item being set at 50px in the example is just for demonstration purposes and is not defined in the actual code. The height adjusts based on the content within.

If I remove the specified height for .container, it will affect the horizontal blue line. I prefer not to rely on setting a height for .container.

Although it may be simple with some JavaScript to dynamically adjust the height, I would rather avoid that and stick to using the height of .container instead. Thank you!

.container {
  display: flex;
  justify-content: space-between;
  align-content: space-between;
  width: 500px;
  height: 125px;
  background: blue;
  flex-wrap: wrap;
}

.item {
  background: red;
  width: 30%;
  height: 50px;
}
<div class='container'>
  <div class='item'> item1 </div>
  <div class='item'> item2 </div>
  <div class='item'> item3 </div>
  <div class='item'> item4 </div>
  <div class='item'> item5 </div>
  <div class='item'> item6 </div>
</div>

EDIT: As it seems that achieving this without JS is not feasible, I will go ahead with using the height specified for .container. For those who prefer a JavaScript solution, here is a JQuery script:

$('.container').height(
    $('.item').height() * 2 +
  (($('.container').width() - 3 * $('.item').width()) / 2)
);

Thank you for your responses!

Answer №1

Achieving two lines and stripes for the .item without specifying height and width is possible by utilizing the flex property.

To achieve this layout, start by adding flex-flow: wrap column to the .container class. This will arrange the .item elements as desired. To create spacing between them, you can use the gap rule.

To control the width, you can use the calc() function to set the flex width for each .item. Here's an example:

flex: calc(100% / 3);

:root {
  --gap: 20px;
}

.container {
    display: flex;
    flex-flow: wrap column;
    gap: var(--gap);
    width: 500px;
    height: 125px;
    background: blue;
    padding: var(--gap);
}

.item {
    flex: calc(100% / 3);
    background: red;
}
<div class="container">
    <div class="item">item1</div>
    <div class="item">item2</div>
    <div class="item">item3</div>
    <div class="item">item4</div>
    <div class="item">item5</div>
    <div class="item">item6</div>
</div>

Answer №2

For those not needing to fully support IE11 & 13, CSS-Grid is a great option: display: grid;. By utilizing

grid-template-columns: repeat(3, 1fr);
, you can easily create a 3 column layout, dividing the space into equal columns (1fr = 1 fraction).

Additionally, the grid-gap property allows you to precisely define the gap space between elements.

It's worth noting that you don't necessarily need to use classes on grid-cards. Instead, you can specifically target them with .container > div.

.container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-gap: 10px;
  padding: 10px;
  width: 500px;
  background: blue;
}

.container > div {
  background: red;
  min-height: 50px;
}
<div class='container'>
  <div> item1 </div>
  <div> item2 </div>
  <div> item3 </div>
  <div> item4 </div>
  <div> item5 </div>
  <div> item6 </div>
</div>

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

Is your prop callback failing to return a value?

I am currently utilizing a Material UI Table component in my ReactJS project and I would like to update a state variable whenever a row is selected or deselected. The Table component has an onRowSelection prop that gets triggered each time a row is is sele ...

Experience the dynamic bouncing marker feature in Next.js React-Leaflet with the powerful tool Leaflet.SmoothMarkerB

I'm a beginner in front-end development and I'm attempting to create a bouncing marker in React-leaflet using the leaflet.smooth_marker_bouncing plugin version 1.3.0 available at this link. Unfortunately, I couldn't find enough documentation ...

Apply express middleware to all routes except for those starting with /api/v1

Is it possible to define a catchall route like this? app.get(/^((?!\/api/v1\/).)*$/, (req, res) => { res.sendFile(path.join(__dirname, '../client/build', 'index.html'));}); ...

Tips on showing a specific div when a button is clicked using jQuery and Bootstrap

In my button group, I have four buttons and I need one specific button to display certain div content when clicked. The displayed content should be based on which button is clicked. Is there a way to achieve this using Twitter Bootstrap jQuery in ASP.NET ...

Exploring React JS Subdomains

I have been developing a MERN application that needs to support dynamic subdomains for each company, like companyname.localhost. In order to make this work, I made an adjustment in my .env file with the line: DANGEROUSLY_DISABLE_HOST_CHECK=true After a us ...

Nested AJAX call yields undefined value

In my Test.vue component, I have a method that is imported into my main.js. I can call its methods like this: this.$refs.test.testMethod(). There is another method in Test.vue called ajaxMethod(), which is defined as follows: function ajaxMethod(){ t ...

axios encountering a 400 bad request error during the get request

I've hit a roadblock for some time now while trying to make a call to my API to fetch data using the GET method. I keep getting a 400 bad request error in Postman, even though I am able to successfully retrieve the data with a status code of 200. I ha ...

Determine the specific value of an HTML table cell by specifying the column name for a specific row

One challenge I am facing is dynamically creating a table using JSON without knowing in advance the number of columns and/or rows that will be generated. I have successfully added a clicked event for the row that gets selected. In every table, there will ...

Integrating Watson Conversation with Oracle Database

Hello everyone, I am currently working on a project where I need Watson to fetch a response manually set from our Oracle Databases. To achieve this, I am using async to access the database sequentially and return the response. Initially, I faced an issue ...

html<script src="" and causing a redirect when button is clicked

My login.html page for logging in can be found in the design folder. <html> <head> <title>Login Page</title> <script src="../Script/login.js"> </script> </head> <body> <h3> Login</h3> ...

Trigger a click event upon page load using jQuery or JavaScript

I tried searching for this functionality on a different website, but it didn't work on my site. Can you help me figure out how to trigger a click event on page load? On one of my pages, a popup box appears when I click on a "project" link. Here is th ...

Extracting data from XML using my custom script

I attempted to extract a specific value from an XML feed, but encountered some difficulties. In addition to the existing functionality that is working fine, I want to retrieve the value of "StartTime" as well. Here is the relevant section of the XML: < ...

Base64 image failing to display in Internet Explorer

Is there a way to efficiently handle the base 64 form of an image in different browsers? The code I have achieves this as shown below: import base64 import requests img=requests.get('https://example.com/hello.jpg') base=base64.b64encode(img.cont ...

What is the method for shifting the expansion panel icon position to the left?

I need the expansion arrow in my app to be on the left side of the panel. However, it currently appears on the right side by default. This is what I have tried: <ExpansionPanelSummary className={classes.panelSummary} expandIcon={<ExpandMore ...

Time for the browser to evaluate javascript code has arrived

We are looking to enhance the speed at which our Javascript files load in the browser. Although our own Javascript files are simple and small, larger libraries like jQuery and KendoUI take a considerable amount of time to evaluate. We are interested in fin ...

Achieving targeted text display on specific viewports using the visible class in Bootstrap

I've recently delved into learning Bootstrap, and I'm experimenting with creating a responsive page where certain divs will only be visible on specific viewports. I used classes like visible-xs, visible-sm, visible-md, and visible-lg for the diff ...

What is the correct way to reference this data element in Ajax?

I am attempting to retrieve the elevation data for 732 meters from the JSON API response below: {"results":1,"data":[{"wind":{"degrees":200,"speed_kts":6,"speed_mph":7,"speed_mps":3,&quo ...

AngularJS $routeProvider is experiencing difficulties with its routing functionality

I am a beginner with Angular and I'm trying to understand how multiple routes can lead to the same view/templateUrl and controller. This is what I have written: angular .module('mwsApp', [ 'ngAnimate', 'ngCookies&ap ...

Using Node.js to parse JSON data fetched from the web

My current challenge involves retrieving and parsing JSON from a web API (https://api.coinmarketcap.com/v1/ticker/?limit=3) in order to extract the name and price_usd fields. For example: [ { ... sample data provided ... } ] The code snippet I am wo ...

What is the best way to connect a relative CSS stylesheet to a master page?

My Java application generates several HTML pages, organized in different directories: html_pages/ | ----> landin_page.html html_pages/details | ----> index1.html html_pages/more_details | ----> index2.html html_pages/css | ...