Eliminate spacing between divs of varying heights

I'm facing an issue with my small gallery of images. Despite having the same width, they vary in height causing the second row to start below the tallest image from the previous row. How can I eliminate these empty spaces while still maintaining the varying heights of the images?

Here is a representation of how my divs are structured:

<div><img src=""></div>
<div><img src=""></div>
<div><img src=""></div>
<div><img src=""></div>
<div><img src=""></div>
<div><img src=""></div>
<div><img src=""></div>
<div><img src=""></div>

https://i.sstatic.net/VQk6y.png

I want to achieve a smooth layout without gaps between images. What steps can I take to address this issue?

Answer №1

Greetings everyone, I want to express my gratitude for taking the time to assist me! :D

After some exploration, I believe I have discovered a straightforward solution that doesn't require JavaScript.

Here is the CSS code:

.gallery{
    max-width: 1150px;
    width: 95%;
    margin: 75px auto 100px;
}

.gallery ul{
    padding: 0;
    margin: 0;
    position: relative;
    -webkit-columns: 3;
    -moz-columns: 3;
    columns: 3;
    -webkit-column-gap: 10px;
    -moz-column-gap: 10px;
    column-gap: 10px;
    column-fill: balance;
}

.gallery ul li{
    display: block;
    margin-top: 10px;
    width: 100%;
}

.gallery ul li:nth-child(1){
   margin-top: 0;
}

.gallery ul li img{
    width: 100%;
    display: block;
}
@media screen and (max-width: 860px){
    .gallery{
        max-width: 700px;
    }
    .gallery ul{
        -webkit-columns: 2;
        -moz-columns: 2;
        columns: 2;
    }
}

@media screen and (max-width: 450px){
    .gallery ul{
        -webkit-columns: 1;
        -moz-columns: 1;
        columns: 1;
    }
}

Also, here is the HTML file where PHP is used to retrieve data from a database where thumbnails and images are stored:

<div class="gallery">
    <?php if(!empty($images)): ?>
        <ul>
            <?php foreach($images as $image): ?>
               <li><img src="<?php echo $image['thumb']; ?>"></li>
            <?php endforeach; ?>
        </ul>
    <?php else: ?>
        <p>No images yet.</p>
    <?php endif; ?>
</div>

It's important to note that the first child of the unordered list has its top margin set to zero. Failure to address this can cause alignment issues in the layout when multiple columns are involved.

For more information on multicomlumns, feel free to visit W3 multicol layout module

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

What is the best way to align all of my content to the center in HTML?

In my web design class, I encountered an issue while creating a page. Currently, my page consists of a navigation bar and an image. I wanted to center both elements using CSS. display: block; margin-left: auto; margin-right: auto I applied this CSS to th ...

Having trouble getting Jquery autocomplete to function properly with a complicated array?

I started with the guidance provided in this post, which was successful. To investigate why it's not functioning, I made a JsFiddle but couldn't figure out the issue. Even when trying to search for results using the first letter of the last name ...

One required positional argument is needed in `update_one()`: 'update' is missing

I've exhausted all possible options, but I can't seem to make it work. Any suggestions on how I can get this code to function properly? I attempted using ajax_data to update the values, but it was unsuccessful. The main goal of this code is to al ...

Handling undefined properties by defaulting to an empty array in ES6

In the code snippet below, I am attempting to extract barNames from an object named bar: const {[id]: {'name': fooName} = []} = foo || {}; const {'keywords': {[fooName]: barNames}} = bar || []; Please note that although fooName exi ...

The $http.get() function in Angular fails to function properly when used in Phonegap DevApp

Trying to retrieve a JSON file in my Phonegap App using angulars $http is causing some issues for me. I have set up this service: cApp.factory('language', function ($http) { return { getLanguageData: function () { return ...

The NodeJS server encountered an issue when attempting to load the JavaScript modules

Hey everyone. I'm currently using Node.js and Express.js for the back end of my web application, but I keep running into issues with the server trying to bind references in the source code. Here's the structure of my app: src/ - static/ - ...

specific css styles only for Safari and Internet Explorer

Imagine a scenario where I have a div with the class 'x': <div class = 'x' /> This div has some CSS properties and what's interesting is that it appears differently in Safari and the latest version of IE compared to other ...

What is the best way to add "m" to the URL for redirecting mobile devices?

Having already installed a mobile detecting plugin for WordPress, my next step is to create a script that can direct users to the mobile version of the site. My idea is to replicate every desktop page on the mobile subdomain and simply add "m" at the begi ...

How can the input validation be displayed in Ajax when the user interacts with it?

When utilizing Ajax, I only want to display validation for the input field that the user is interacting with, not all validations at once. Currently, my script shows all validations simultaneously when any input is filled out. How can I modify my code so t ...

Issue with Access Denied Error in Internet Explorer 11 when Using AngularJS

Every software development process consists of two essential components. FIRST, the hard work of developing the application. SECOND, the even harder task of making it compatible with the notorious Internet Explorer. Currently, we have an AngularJS (v1.3.1 ...

How to eliminate certain elements from the DOM in Angular 5

I'm facing a minor issue in my Angular/Typescript project that I can't seem to resolve. I am still new to these technologies and struggling with removing certain DOM elements. The content is auto-generated with specific CSS classes, and unfortuna ...

Retrieving data from a JSON file at 10-minute intervals with Ajax and visualizing it on Google's globe API

After downloading Armsglobe, a globe API provided by Google to draw lines in countries using their names, I noticed that the original code does not fetch JSON data periodically. I attempted to use a simple setTimeout() function in dataloading.js to address ...

Tips for organizing a Bootstrap 4 menu overflowing with elements

I'm struggling to figure out how to organize a Bootstrap 4 menu with numerous links. Currently, when I include too many links, the navbar disregards the container and expands its width beyond the container. Here is an image for better clarification: ...

An error occurs when attempting to redirect with getServerSideProps

When I am logged in, I want to redirect to the /chat page using auth0 for authentication. The error seems to be related to returning an empty string for props, but it does not impact the website as redirection works correctly. The main issue here is the in ...

Create an XML file with recurring elements based on JSON data

Currently, I am utilizing the xmlBuilder library within Nodejs to generate XML from a prepared JSON object. My approach involves crafting the JSON structure first and then transforming it into XML using Javascript as the coding language. The specific XML ...

How to ensure a table in MaterialUI always maintains full width without requiring horizontal scrolling in CSS?

After attempting to allocate each widthPercent value on the TableHeader so they sum up to 100%, I am still experiencing the presence of a scroll bar. I have tried setting fixed widths for each column, but this results in excess space on the right side dep ...

Error occurs when running Visual Studio Code locally - variable not defined

After successfully going through a Microsoft online demo on setting up an httpTrigger in Visual Studio Code with JavaScript to upload it to Azure Functions, I decided to customize the code for a specific calculation. I managed to get the calculation done a ...

PHP Form encountering error due to JSON decoding following an AJAX request

After extensive research and much confusion, I have finally decided to seek help here. I am able to make my AJAX request post successfully in every format except JSON. I am eager to understand JSON so that I can start using it right away instead of learni ...

What causes two elements with display: inline-block; position: absolute; to overlap instead of appearing side by side?

It is recommended to use position: relative; in order to achieve inline block behavior for both elements and prevent them from overlapping. This positions the elements inline next to each other as they are recognized as blocks. When using position: absolu ...

Strategies for creating a grid-inspired layout: tips and tricks

Recently, I've been tasked with creating a catalogue section for our e-commerce site. My designer came up with this layout which I find really appealing, but I'm having trouble figuring out how to implement it. I attempted using tables, but it di ...