Looking for assistance in reducing the vertical spacing between divs within a grid layout

Currently, I am in the process of developing a fluid grid section to showcase events. To ensure responsiveness on varying screen resolutions, I have incorporated media queries that adjust the size of the div elements accordingly. When all the divs are uniform in height, the layout looks great. However, it presents issues when the divs have different heights, resulting in unsightly vertical gaps between them. Is there a way to address this? I suspect it may require more than just CSS and might involve some JavaScript work. I have included two images for reference: one depicting the current appearance and the other illustrating the desired look. Find the relevant HTML code below.

<style>
body {
    background-color:#dedede;
    margin:0;
    font-family:Verdana, Geneva, sans-serif;
    font-size:11px; 
}
#pagewrap {
    width: 100%;
    margin: 10px auto;
}
.box {
    box-sizing:border-box;
    padding:10px;
    margin:6px;
    max-width:220px;
    border:solid 1px #ccc;
    background-color:#fff;
    float:left;
}
@media screen and (max-width: 1200px) {
    .box {
        width:19%;
        margin:.5%;
    }
} 
@media screen and (max-width: 980px) {
    .box {
        width:23.75%;
        margin:.5%
    }
}
@media screen and (max-width: 650px) {
    .box {
        width:31%;
        margin:1%;
    }
}
@media screen and (max-width: 565px) {
    .box {
        width:46%;
        margin:2%;
    }
}
@media screen and (max-width: 360px) {
    .box {
        width:90%;
    }
}
</style>
</head>
<body>
<div id="pagewrap"> 
<div class="box">Your event content here!</div>
// Repeat above line as needed

Current Layout: https://i.stack.imgur.com/WtcPn.jpg
(source: asingularcreation.com)

Desired Layout: https://i.stack.imgur.com/yW36y.jpg
(source: asingularcreation.com)

Any assistance with resolving this issue would be greatly appreciated!

Answer №1

If you are targeting modern browsers only, consider implementing CSS3 multi-column layouts.

DEMO: http://jsfiddle.net/Vr4Dh/

#pagewrap {
    width: 100%;
    margin: 10px auto;
    -webkit-column-width: 220px;
    -moz-column-width: 220px; 
    column-width: 220px; 
}
.box {
    box-sizing:border-box;
    padding:10px;
    margin:6px;
    max-width:220px;
    border:solid 1px #ccc;
    background-color:#fff;
    display: inline-block;
    vertical-align: top;
}

For a more versatile solution across different browsers, you can utilize the Vanilla Masonry Library if jQuery is not being used, or opt for the Masonry jQuery plugin. Both options offer the functionality you need.

Answer №2

I discovered this effective solution that has been working incredibly well for me.

When utilizing jQuery, I came across a function called CollManag that significantly improved the functionality of my website. By optimizing the number of columns displayed based on the window width, this function enhanced the overall user experience. Additionally, it allowed for easy integration with various plugins to further enhance the layout and design of the webpage.

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

Responsive design involves ensuring that web elements such as divs are properly aligned

I am currently working on aligning 2 divs in a specific way that is responsive. I would like the right div to stack on top of the left div when the screen width reaches a certain point, as opposed to them both taking up 50% of the container's width. ...

What is the best way to call a method within a TypeScript class using its name as a string while already inside the class itself?

Currently, I am developing a class that automates the creation of routes for Express and invokes a function in a controller. However, upon trying to execute this[methodName](req, res), I come across an error message stating: 'Element implicitly has an ...

Retrieve an image using screen resolution parameters [using only HTML]

During a recent interview, the interviewer posed an interesting question regarding 2 images: There is one large resolution image that needs to be displayed on laptops and desktops. There is also a small image that should only be shown on mobile devices. ...

Is it possible to embed HTML code within JavaScript strings?

Is my approach to inserting HTML into a JavaScript string correct? In particular, I want to insert an HTML link into a div tag using JavaScript. Here is the HTML: <div id="mydivtag"></div> And here is the JavaScript code: document.g ...

What is the best way to position a small image within a menu?

Is there a way to adjust the position of the arrow image within the <li> element without affecting the layout of the unordered list? Below is the code snippet for reference: body { margin: 0; padding: 0; } nav { width: 100%; background: # ...

Axios and Postman generate unique X-CSRF tokens

Why does the X-CSRF token I receive from my axios request differ from the one I get in Postman? Here is how I am retrieving it: headers: { "X-CSRF-Token": "FETCH" } Furthermore, I am unable to use the X-CSRF token from my axios request in Postman as it ...

Retrieve data from MongoDB using the unique identifier (_id) and additional conditions with Express

Below is the code I am currently working with: PostCategory.find({categoryid:category._id.str},function(err,postcategories){ if(err) return next(err); Post.find({_id:postcategories.postid},function(err,posts){ if(err) ...

What is the best way to set conditions for document side script?

I'm struggling to disable the horizontal scroll when the viewport width is 480px or less. The script that controls the scroll behavior on my website looks like this: <script> $(function () { $("#wrapper").wrapInner("< ...

The background refuses to cooperate, soaring upward only to be abruptly sliced in two

I am in the process of creating a website login window with an image background, but I'm experiencing issues where the image is being cut in half and moved up. Here is the code snippet I am currently using: .loginbody { background: url(img/LoginB ...

React Material-UI: Trouble with Checkbox Toggle

I'm encountering an issue with my React code where the checkbox is not toggling when clicked. Here is the link to the codesandbox: https://codesandbox.io/s/inspiring-kirch-q6p4h The checkbox state initialization looks like this: const [checkbox, set ...

The lengthy email exceeds its limits

Take a look at this code snippet: <div className='mt-[3vh] flex h-1/3 min-h-fit w-[80%] min-w-[300px] flex-col content-center items-center justify-center rounded-2xl bg-white shadow-[0_0_8px_rgba(0,0,0,0.2)]'> {user?.image && ...

Incorporating an additional row into a material table

Currently, I have implemented a mat-table with various features including drag and drop functionality and dynamic columns. However, I am facing an issue while trying to add row filters under the table header. I attempted to simply insert a <mat-row> ...

Troubleshooting the challenges with jQuery's next().addClass() and prev().addClass() functions

I am attempting to create a slider feature. I have four different contents that I've positioned consecutively, but made them invisible initially. I defined a class called active-client with the attribute display: flex. Using jQuery's addClass() m ...

What is the process for importing a sprite sheet along with its JSON file into my Phaser game?

Currently, I am in the process of developing a game using the powerful phaser game engine. To enhance the visual appeal of my game, I decided to create a sprite sheet and successfully downloaded it. The sprite sheet consists of a 256 × 384 .png file ...

What is the best way to locate the closest points using their positions?

I have a cluster of orbs arranged in the following pattern: https://i.sstatic.net/9FhsQ.png Each orb is evenly spaced from one another. The code I am using for this setup is: geometry = new THREE.SphereGeometry(1.2); material = new THREE.MeshPhongMateri ...

In need of clarification on the topic of promises and async/await

I have been utilizing Promises and async/await in my code, and it seems like they are quite similar. Typically, I would wrap my promise and return it as needed. function someFetchThatTakesTime(){ // Converting the request into a Promise. return new ...

After attempting to install @mui/system, I encountered an error. I decided to uninstall it, but now I am consistently facing this

ERROR in ./node_modules/@mui/material/Unstable_Grid2/Grid2.js 6:14-25 export 'createGrid' (imported as 'createGrid2') was not found in '@mui/system/Unstable_Grid' (module has no exports). Encountering an issue after installin ...

Express/NodeJS encountering a CORS problem, causing services to be inaccessible in Internet Explorer

Currently, I am working on a REST-based service implemented in Express/NodeJS. The code includes CORS (Cross Origin Resource Sharing) implementation to allow services to be consumed from browsers like Chrome and Firefox. However, there seems to be an issue ...

Sending a message from a Vue.js application to Contact Form 7 using the Wordpress REST API - a step-by-step guide

I recently added Contact-Form-7 to my WordPress admin panel, which generated an API Endpoint for me at http://localhost/wordpress/wp-json/contact-form-7/v1/contact-forms Attempting to send a POST request to this endpoint using the following code: data() ...

NodeJS domain error handling failing to catch ReferenceError exceptions

I'm currently facing some challenges with domains in NodeJS. I've set up middleware functions to wrap every call in my web application within a domain in order to capture errors, process them, and return informative error messages. While this se ...