Steps to design a grid layout featuring elements (divs/spans) in precise square dimensions, each showcasing unique image backgrounds

I've been working on a website that showcases an ever-evolving gallery of fantasy art. Currently, I've encountered a roadblock in figuring out how to proceed with something that's not functioning as expected. I tried using Masonry and Wookmark without success, so now I'm exploring other options. My goal is to dynamically create either divs or spans within the grid with the class identifier images and set their backgrounds to specific image sources that "cover" the area while being centered. Essentially, I want to create a grid of square windows showcasing these images, which can be clicked to open a lightbox (that I've already created successfully). However, at the moment, although the images are displaying, the containers seem compressed with no padding on the sides.

Truth be told, I'm uncertain about how to handle relative/absolute positioning and inline/block display properties. I suspect this is where my mistake lies, but I lack a clear understanding of what these concepts involve.

Snippet of the HTML:

<div id="grid" class="grid"></div>
<br>

CSS:

.grid {
  z-index:2;
  display: inline-block;
}

.images {
  display: inline-block;
  position: relative;
  width: 25%;
  height: 25%;
  z-index: 2;
  padding-right: 0.25em;
  padding-left: 0.25em;
  padding-top: 0.5em;
  background-size: cover;
  background-attachment: fixed;
  background-repeat: no-repeat;
  background-position: center;
}

Javascript:

var mix = shuffle(Object.keys(backInfo));                 


function unlockImages () {      
  setTimeout(function () {          
    if (mix !== undefined) { 
      var input = mix.shift();
      var entry = backInfo[input];
      var elem = document.createElement("div");
      elem.setAttribute("class", "images");
      elem.setAttribute("id", input);
      elem.setAttribute("title", entry.caption);
      elem.setAttribute("onclick", "javascript:changeImage(" + input + ");");
      document.getElementById("grid").appendChild(elem);
      document.getElementById(input).style.backgroundImage = "url(" + entry.image + ")";
      $("#" + input).fadeTo(0,0);
      $("#" + input).fadeTo(20000,1);
      unlockImages();
    }
  }, 0)
}

To see a live preview of the current progress, visit:

Answer №1

It appears that the issue you are facing pertains to CSS. I have made some adjustments to your CSS code and arrived at the following solution:

.grid {
  z-index:2;
  display: inline-block;
  height: 500px;
  width: 1500px;
}

.images {
  display:inline-block;
  position:relative;
  width:25%;
  height:25%;
  z-index:2;
  margin-right: 0.25em;
  margin-left: 0.25em;
  margin-top: 0.5em;
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
}

Here are a few things to keep in mind when dealing with your CSS:

  1. When setting a percentage width x height, the parent container must have a designated value. Since the .grid class does not specify a height value, the images appear squished due to taking up 25% of zero height.
  2. Using background-attachment: fixed; prevents the picture from automatically resizing, which I assume is your desired outcome.
  3. If you want spacing between elements, utilize margin instead of padding. Padding affects the interior of an element, while margin creates space between elements as demonstrated in the revised CSS above. Hope this helps!

Answer №2

If you're looking to generate a dynamic grid and populate images in each box, you can use the following code snippet.

  1. Start by creating a container div with the id "wrapper".

  2. Include this Javascript function in your code and call it as needed:

    function GenerateGrid() {

       var rows = 2;
       var columns = 2;
    
        $("#wrapper").empty();
    
        for (var i = 0; i < rows; i++) {
    
            var $row = $("<div />", {
                class: 'row'
            });
    
            // Add columns to the row object
            for (var c = 0; c < columns; c++) {
    
                var $square = $("<div />", {
                    class: 'square' 
                });
    
                //Set your image source here
                $square.append("<img></img>");
    
                $row.append($square.clone());
            }
    
            $("#wrapper").append($row.clone());
        }
    }
    

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

The header is visible above the navigation bar when scrolling on mobile, but it should be hidden

I am facing an issue with fixed content on mobile positioned above a Bootstrap navbar. The problem arises when scrolling down, causing the navbar to move up by 50px (the height of the content above the navbar). Everything seems to work fine initially, but ...

"Unleashing the power of plugins in your Nuxt.js store: A step

I am facing an issue with my gtag (analytics plugin) where I can access it on my components but not on my store. Any suggestions are welcome. Thank you. plugins/vue-gtag.js import Vue from "vue" import VueGtag from "vue-gtag" export d ...

Using jQuery to create transitions when a class is changed and adding a delay to the transition

If you want to check out the section I created on CodePen, feel free to visit it by clicking here. I've noticed that my JavaScript code has a lot of repetitive elements and I'm looking to optimize it for better performance. Any advice on how I c ...

Initialization of Arrays with Default Values

I have taken on the task of converting a C++ program into JavaScript. In C++, when creating a dynamic array of type float/double, the entries are automatically initialized to 0.0; there is no need for explicit initialization. For example, a 1-D vector of ...

Shut down the Pub/Sub client following a transmission via socket.io-mongodb-emitter

I am facing an issue with emitting a message into a socket.io room using socket.io-mongodb-emitter. The problem lies in the fact that my script never exits as it maintains a connection to mongodb. Take a look at the examples below and provide some suggest ...

Update the styling of each div element within a designated list

Looking for a way to assist my colorblind friend, I am attempting to write a script. This is the layout of the page he is on: <div class="message-pane-wrapper candy-has-subject"> <ul class="message-pane"> <li><div style=" ...

Accessing properties in JSON data with AngularJS

I am experiencing issues with accessing a JSON object returned from an $http call in my AngularJS app. I have provided the code snippet below, but it seems that nothing is being rendered on the HTML. Can anyone please assist me in identifying what I might ...

In iOS devices, the Ionic framework restricts the ability to open links in a new tab using the ng-href attribute

In my quest for mobile functionality, I'm aiming to implement a feature on devices where tapping will open 'codepen.io' (triggered by ng-click), and tap and hold will display a context menu with the option to 'Open In New Tab', red ...

Ways to reduce lag while executing a for loop

How can I optimize my prime number generation process to avoid lagging? For example, is there a way to instantly display the results when generating primes up to 1000? HTML: <!DOCTYPE html> <html> <meta name="viewport" content="width=dev ...

The issue with Console Logs and Alerts not functioning properly

It seems like the console.log and alert() functions are not working in any of my JavaScript files. I am utilizing Gulp to concatenate and compile a group of .js files (see gulpfile.js below). I suspect that the issue lies here, as the alerts and console l ...

Utilizing AJAX to Access JSON Arrays

After clicking a button, I want to append specific parts of a JSON array (received from a server) to a table. However, I'm facing an issue where I am unable to add these parts to the table. Here is the JSON Array that was received from the server: {& ...

Can you identify the specific name of the IE CSS bug affecting double vertical padding?

(Just when I thought I've encountered all the strange IE CSS bugs, here comes another one. Is there a name for this double-vertical-padding bug?) After creating a simple test case that worked perfectly in browsers like FF and Opera, I was surprised t ...

Is there a way to displace a 2D triangle within a webgl shader?

I am facing a challenging situation while trying to implement conservative depth rendering, as described in CPU gems. My primary obstacle is enlarging the triangle, and it seems like I might have encountered the "stupid" phase. To illustrate the current s ...

Organizing the order of DIVs from desktop to smartphone

Hello there, I trust you are doing well. Currently, I am working on making my desktop site responsive. Below is the layout I have on desktop at the moment. IMAGE_1_DIV TEXT_1_DIV TEXT_2_DIV IMAGE_2_DIV IMAGE_3_DIV TEXT_3_DIV As you can see, th ...

JavaScript was unable to locate the requested URL on the server

After successfully deploying and accessing the URL using Firebase's hosting feature, everything seems to work fine. However, when I try to access a specific endpoint like this: https://*******.web.app/api/send, I encounter the following error message: ...

Angular: creating a template with a directive inside another directive

Let me share a simple example... Here is the code snippet: angular .module('app', []) .directive('parentDirective', parentDirective) .directive('childDirective', childDirective); function parentDirecti ...

When utilizing Next.js with useEffect, axios, and router.query, the data displayed may not refresh properly when changing

I'm currently working on a project using Next.js, where I have a component that utilizes axios and the useEffect hook to fetch data. The data is fetched based on the router.query object for dynamic routing purposes. However, I've encountered an i ...

Is client-side rendering the new trend, bypassing traditional server-side rendering?

I'm exploring the idea of rendering my pages on the client side to reduce server load and minimize traffic. Typically, the first request to the server requires it to render the requested page and then send it to the user. Once the user interacts with ...

The HTML content retrieved through an ajax service call may appear distorted momentarily until the JavaScript and CSS styles are fully applied

When making a service call using ajax and loading an HTML content on my page, the content includes text, external script calls, and CSS. However, upon loading, the HTML appears distorted for a few seconds before the JS and CSS are applied. Is there a sol ...

The relatedTarget property of the Event object is always set to undefined

Within Bootstrap events, we have access to event.relatedTarget in the various available events. For example, I am utilizing shown.bs.modal. Normally, event.relatedTarget holds the button object from where we click and activate the modal using an onclick ev ...