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

Choosing jQuery over JQuery Mobile for a standard web application to effectively manage different devices

Creating a Unique Web Application In the works is a unique web application, similar to Trello, that divides a page into columns where tasks/cards can be added and moved between them. This desktop-focused platform will feature an information column on the ...

How can I combine various array values of equal length using a delimiter to create one final array?

I am trying to combine the values from 3 separate arrays, all of which have the same length. var title = ['title 1','title 2','title 3']; var description = ['description 1','description 2','descri ...

The cascading style sheet does not have any effect on the layout of the tables within the

I am trying to apply a CSS style to give all tables on my HTML pages a 1px border width. However, for some reason, the borders are not showing up in my HTML files! What could be causing this issue? <!-- <style type="text/css"> --> body{backg ...

Securing form submissions in Express JS: Best practices for protecting your data

In order to enhance security, the loginform.html located in the public folder sends the username and password input by the user to a server route '/login' for authentication. Server-Side Code: var express = require('express'); var app ...

Utilizing the Vue feature of dynamic route naming within a component's function

Currently, I am working on creating a dynamic view rendering using Vue and Laravel. However, I am facing difficulty in understanding how to pass the dynamic parameter to the component function. Router.map({ '/cms-admin/:page': { comp ...

Performing two separate AJAX calls within a single script, but utilizing a specific variable from the URL in one of the calls

The purpose of this script is to make two API calls, extract the "id" from the first call, and use it in the second call: var contentType ="application/x-www-form-urlencoded; charset=utf-8"; if (window.XDomainRequest) contentType = "text/plain"; $. ...

Share the hyperlink to a webpage with someone else

In my SQL command, I have a unique feature that retrieves the complete URL value of the current page: [##cms.request.rawurl##]. This code returns the entire URL. I need to send this address to another page and load it into a special div called "load-fac". ...

Automatically updating markers on Google Maps v3

I'm utilizing the capabilities of Google Maps V3 to showcase various pins. My goal is to update these markers periodically without interfering with the current location or zoom level on the map. I aim for the markers to refresh every x seconds. How c ...

How about implementing built-in validation for Vue Headless UI Listbox (Select) element?

I need assistance in integrating native validation support into the Vue3 or Nuxt 3 Vue Headless UI Listbox (Select) component. It appears that direct support is not available, so I am looking for the best and most straightforward approach to achieve this. ...

selenium tutorial: Testing tooltip functionality with Python

<div class="icon_png information icon_baggageyes" title="getTooltip()"></div> Here, a tooltip is displayed using the getTooltip() function. Is there a method to retrieve the return value of the function for testing with Selenium? ...

Updating the properties of items in an array using React

Today, I was working on React and found myself stuck due to my limited JavaScript knowledge. I am trying to update the "name" property value of any object in this array. Check out the Codesandbox demo: https://codesandbox.io/s/dank-rain-udjcxe?file=/src/ ...

Increase the value by one of the number enclosed in the <h3> element

I have a variable number of <h3> tags with the same class .love_nummer <h3 class="love_nummer">1</h3> Each of these tags contains a number, and alongside each .love_nummer tag is another tag with the class .give_love <h3 class="give ...

Numerous SVGs sharing identical IDs

Is it possible to include multiple SVGs on an HTML page and utilize the same IDs in each of them? <div> <svg height="0" width="0"> <clipPath id="svgPath"> ........ </svg> <svg height="0" width="0"> < ...

What is the best method for incorporating jQuery code into a separate file within a WordPress theme?

I'm fairly new to working with Javascript/jQuery, so please be patient with me. Currently, I'm in the process of creating a custom WordPress theme where I've been using jQuery to modify the main navigation menu generated in my header file ( ...

Which internet browsing engine does Android leverage for phonegap applications?

Currently, I'm working on incorporating CSS animations into a phone gap project. Surprisingly, the animations work flawlessly on an iOS device but encounter issues on my Android device. Strangely, elements like dashed borders are not even showing up. ...

Challenge with constructing HTML structures

I created a table in HTML: <table cellpadding="0" cellspacing="0" border="0" style="width:1000px" id="maintable"> <thead> <tr> <th class="asc" width="30"><h3>ID</h3></th> <th width="200">&l ...

Can anyone recommend a user-friendly JavaScript dialog box compatible with jQuery that is mobile-responsive?

Mobile browsers. Using Jquery dialog alert box. Avoiding the use of alert() due to its unattractive appearance in web browsers. In the process of creating a website for both mobile and web platforms, seeking a dialog box that is compatible with both. ...

The first item in Swiper is incorrectly displayed after the initial cycle, even though the data is accurate

Currently, I am incorporating the slider functionality in Vue using the Swiper framework. Although everything seems to be functioning properly, there is a minor issue that arises when filtering the data and completing the first cycle after scrolling. The f ...

Is the order in which properties are executed always the same in CSS rules?

Have you ever wondered about the way browsers handle CSS properties within the same rule? The topic of rules precedence has been discussed at length, but this specific question focuses on the execution order by the browsers. In my view, I have always assu ...

Detecting when an object exits the proximity of another object in ThreeJS

In my ThreeJS project, I have planes (Object3D) flying inside a sphere (Mesh). My goal is to detect when a plane collides with the border of the sphere so that I can remove it and respawn it in a different location within the sphere. I am wondering how I ...