Tips for arranging div elements in a grid-like matrix layout

I am facing a challenge in arranging multiple rectangular divs into a grid structure with 10 columns and 10 rows. The CSS styles for the top, bottom, left, or right positions must be in percentages to accommodate zoom in and out functionality without overlapping issues. Despite my efforts, the divs are stacking vertically instead of forming a grid layout as intended. Here is the code snippet I have been working on:

setCss = function($divId,$len) {
    alert("xmlLength is :"+$len);
    alert("set CSS::"+$divId);
    if ($len<3)//(i%2==0)
    {
        var size = 10;

        $("div#"+$divId).css("top",size*$len+"%");
        $("div#"+$divId).css("left",size*$len+"%");
        $("div#"+$divId).css("transform","none");
        $("div#"+$divId).css("margin","10px");

    }
    if (i>=3 )
    {
        var size = 10;
        $("div#"+$divId).css("top",size*$len+"%");
        $("div#"+$divId).css("left",size*$len+"%");
        $("div#"+$divId).css("bottom",size*$len+"%");
        $("div#"+$divId).css("right",size*$len+"%");

        $("div#"+$divId).css("transform","none");
        $("div#"+$divId).css("margin","10px");

    }
};

I have experimented with various combinations but have not achieved the desired result yet. Any guidance on how to tackle this issue would be greatly appreciated. Thank you!

Answer №1

If you're looking to organize columns and rows, here are a few options:

  • One option is to create a table.
  • You can also set display:inline-block for the divs, and every 10th div add an extra empty div with display:block.
  • Alternatively, you can use float-left for the divs, and after every 10 divs, add clear:right to break to a new line.

For the second and third options, make sure to set min-width:[10*divWidth] for the container.

Edit:

It appears that absolute positioned divs are being used.

In this case, you can loop through all the divs with an index i. If i%10 == 0, increase the top property and reset the left position.

Or, for a more efficient solution without tracking current top and left values,

var cols=10,
    rows=5,
    wid=10,
    hei=20,
    d=document.createElement('div');
d.className='cell';
d.style.width=wid+'px';
d.style.height=hei+'px';
for(var i=0;i<cols*rows;i++){
    var c=d.cloneNode(false);
    c.style.top=Math.floor(i/cols)*hei+'px';
    c.style.left=i%cols*wid+'px';
    document.body.appendChild(c);
}

Check out the implementation in this jsfiddle: http://jsfiddle.net/4pj74/

Edit 2:

If you prefer to create all elements first and then position them,

// Setting up variables
var cols=10,
    rows=5,
    wid=10,
    hei=20,
    d=document.createElement('div'),
    wrap=document.getElementById('wrapper');
d.className='cell';
d.style.width=wid+'px';
d.style.height=hei+'px';

//Creating elements
for(var i=0;i<cols*rows;i++){
    var c=d.cloneNode(false);
    wrap.appendChild(c);
}

//Positioning elements
for(var i=0;i<wrap.childNodes.length;i++){
    setCSS(i);
}
function setCSS(i){
    var el=wrap.childNodes[i];
    el.style.top=Math.floor(i/cols)*hei+'px';
    el.style.left=i%cols*wid+'px';
}

(I'm using

<div id="wrapper"></div>
as the container instead of directly appending to the body)

View the updated code here: http://jsfiddle.net/4pj74/3/

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 Formik form is not being populated with data from the API

While working on a functional component in ReactJS, I created a simple form using Formik. The input fields in my form are supposed to fetch data from an API when the component mounts. To achieve this, I utilized fetch and useEffect. However, after fetching ...

What is preventing Angular from loading on this Plnkr?

I've spent time researching my problem and testing various solutions, but I still can't seem to resolve it. Angular doesn't appear to be loading correctly in Plunker for some reason. I've heard that ng-app is no longer supported in ne ...

Combine two sets of JavaScript objects based on their positions using Underscore.js

Data Set 1: {id: "01", name: "John Doe", age: "25", city: "New York", country: "USA"} Data Set 2: [{key:'id', value:'01'},{key:'name', value:'John Doe'},{key:'age', value:'25'},{key:'city& ...

Can JavaScript be used to mimic selecting a location from the autocomplete dropdown in Google Maps API 3?

Currently, I am attempting to automate the process of selecting items from the autocomplete dropdown in the Google Maps API v3 places library using jQuery. However, I am facing difficulty in identifying the necessary javascript code to select an item from ...

Having issues with the Vue.js documentation example not functioning properly in Codepen?

My goal is to replicate a checkbox example from Vue.js's documentation. However, when I import Vue into codepen.io and copy the code for multiple checkboxes into the JS field, then paste the HTML into the designated field, something isn't working ...

A guide on implementing a .click function with jQuery

I have a code snippet that is supposed to add 100 to a number in a MySQL table when a button is clicked. However, the code does not work as expected. When I click the button, nothing happens, but if I refresh the page, it adds 100 to the number. Can some ...

Tips for appending the id of an active element to a URL

My goal was to include the id value of the active element in a URL and then redirect to that URL with a button click. HTML <div class="icon" tabindex="0" id="company"> <img src="company.png"> </div> <button type="submit" onclick= ...

Error TS2307: Module 'calculator' could not be located

Running a Sharepoint Framework project in Visual Studio Code: This is the project structure: https://i.stack.imgur.com/GAlsX.png The files are organized as follows: ComplexCalculator.ts export class ComplexCalculator { public sqr(v1: number): number ...

Is HTML-escaping necessary when implementing regex checks?

As I develop a web application that takes user input through HTML inputs and forwards it to my tomcat server for processing, my current workflow is as follows: Client JS -> collect HTML input -> perform regex validation -> if successful -> send data via ...

Deactivate hover effects and media queries for Material UI controls in all states

Since I am using a touch-capable monitor, I noticed that hover styles are not showing up on any controls. Specifically, when I hover over a Material UI button, I see the following styles: https://i.stack.imgur.com/uwBpt.png Is there a way to disable all ...

What is the best way to show a loading spinner as my Next image component loads, especially when there is an existing image already being displayed?

I'm trying to incorporate a loading spinner or any other HTML element while an image is being loaded. Currently, I am utilizing the ImageComponent to showcase images in a random movie generator. Although I managed to make the spinner work for the init ...

I can't seem to figure out why my characters keep disappearing from the HTML string when I attempt to dynamically add HTML using JavaScript

I am currently facing an issue with dynamically adding links to a page. The links are being added successfully, however, the '[' and ']' at the beginning and end of the line are disappearing. Here is the code snippet from my .js file: ...

The situation arose where Next.js could not access the cookie due to

Hi there, I'm new to web development and recently encountered a challenge with my next.js app. I'm currently following Brad Traversy's course on udemy to learn basic CRUD functions. In this component, I am trying to fetch user data from my ...

Despite being logged, the current value of firebase.auth().currentUser in Firebase is null

I have coded a query in my service.TS file that displays the "state" of items based on the UID of the logged-in user: getLists(): FirebaseListObservable<any> { firebase.auth().onAuthStateChanged(function(user) { if (user) {console.log("blah", fir ...

selectize.js typescript: Unable to access values of an undefined object (reading '0')

I've been working on incorporating selectize.js into my project using webpack and typescript. After installing selectize.js and the necessary types, I added the following to my code: yarn add @selectize/selectize yarn add @types/select2 Within my c ...

In my opinion, CSS3 transform translateZ can be likened to scaling in some way

There are instances where I believe that the translateZ and scale properties produce similar effects, akin to zooming in or out. I suspect there is a mathematical relationship between them. If I know the value of one, such as translateZ(-1000px), along wi ...

Contrast: Colon vs. Not Equal Sign (Typescript)

Introduction Hello everyone, I am new to Typescript and currently grappling with some fundamental concepts. When defining a parameter for a function, I typically specify the type like this: function example(test: string){...} However, as I delve deeper ...

JQuery validation for phone number format 01x-xxxxxxxx

Currently, I am using jQuery Validate to validate the form. In order to validate the phone number field, I have implemented the following code: The phone number should be written in the format 01x-xxxxxxxx var phonereg = /^[0-9]{3}\-[0-9]{7}$/; H ...

Having trouble with jQuery functionality when using Laravel 7 mix

Hey there! I'm currently using Laravel Mix to compile all my JS files, but I'm running into an issue with jQuery not working. I've tried adding the defer attribute, but no luck. Can anyone help me troubleshoot this? Thanks! Here's a sn ...

Is there a way to dynamically adjust the form action based on whether or not JavaScript is enabled?

Is there a way to make a form default to calling a JavaScript ajax function for output, but switch to a PHP page if the user doesn't have JavaScript enabled? <form class="form-inline" role="form" action="javascript:search();"> <div class=" ...