How to make divs occupy the entire space of a parent div?

I've been scouring the website for a solution, but nothing I've found has been helpful. I'm attempting to create a grid within a containing div where a default (and eventually user-specified) number of divs will fill up the space. I'm trying to determine how to adjust the size of the divs I add to the parent based on the quantity added, always ensuring the div is filled, if that makes sense. For example, if I input 9, I would like to see 3 rows and 3 columns. If I input 62, I am aiming for 16 rows and 16 columns, while still filling up (or getting close to) the containing div. I have a JSfiddle setup here: https://jsfiddle.net/psyonix/1g9p59bx/1/ This is the current code:

    var d = ("<div class='square'></div>");

function createGrid(numSquares){
    for(var i = 0; i < numSquares; i++){
            $('#g_area').append(d);
    }

    var squareSize = Math.floor(580/numSquares );
    $('.square').height(squareSize);
    $('.square').width(squareSize);
};


$(document).ready(function(){
    createGrid(64);

});

Answer №1

Your main issue was incorrectly setting the square size to 1/64th of the height instead of 1/(64^.5) of the height. This resulted in only one row being created. Explore the updated code snippet here: https://jsfiddle.net/1g9p59bx/7/

var d = ("<div class='square'></div>");

function createGrid(numSquares){
    var gridContainer = $('#g_area'); 
    for(var i = 0; i < numSquares; i++){
            gridContainer.append(d);
    }

    var squareSize = Math.floor(580/(Math.sqrt(numSquares)) );
    $('.square').height(squareSize);
    $('.square').width(squareSize);
};

$(document).ready(function(){
    createGrid(64);
});

Answer №2

If I were to tackle this, I'd develop a jQuery plugin specifically for this purpose. This plugin can be invoked in any container of your choice by simply using:

containerForGrid.createGrid(cols, rows)

(function($){

$.fn.createGrid = function(cols, rows) {
  
  // obtain the width and height of the surrounding container
  var w = this.width()
  var h = this.height()
  
  // compute the width and height of each cell
  var colWidth = w / cols
  var rowHeight = h / rows
  
  // iterate over all rows
  for(var i = rows; --i;){
  
      // iterate over all columns
      for(var j = cols; --j;){
      
        $('<div>').css({
          width:colWidth,
          height:rowHeight,
          float:'left'
        }).appendTo(this)
      
      }
  
  }
  
}

})(jQuery)

jQuery('div').createGrid(10,10)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="width:1000px;height:500px">

</div>

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

Vertical button group within a Bootstrap 5 input group

How can I create an input-group for increasing or decreasing numbers? Below is the code I have: <div class="input-group input-group-sm"> <input type="text" class="form-control" placeholder="0.9"&g ...

Activate lighting in Three.js with a simple click

I successfully loaded a sphere mesh with Lambert material. Now, I am trying to add a light source to the point where there is an intersection after clicking. target = object that was clicked. to = vector3 of my click. When the dblclick event listener is ...

Using different browsers can cause web fonts to appear rough and pixelated

While exploring the issue of "jagged" or "pixelated" fonts, I made an interesting discovery. After creating a website locally and viewing it in Firefox, the font from Google Webfonts appeared flawless - almost like it was straight out of Photoshop. It wasn ...

Determine in Typescript if a value is a string or not

In my code, I have a component: export type InputData = string | number | null; interface InputData { data?: string | number | null; validate: boolean; } const App: React.FC<InputData> = ({ data = '', validate = true, }) => ...

Disappearance of jQuery Ui Spinner on Woocommerce cart page occurs after cart update

I've encountered a problem and am struggling to find a solution. Currently, I am utilizing the jquery ui spinner in the product quantity section to set minimum and maximum quantities for each product. This allows users to increase the quantity by the ...

There appears to be a malfunction with WebRupee

I have incorporated the new rupee sign into my website to represent Indian currency. Below is the code snippet I used: For the script, I included " and also added the following: <span class="WebRupee">Rs.</span> 116,754.00 To style it using ...

Using jQuery to dynamically disable a textbox when a checkbox is checked

I'm trying to implement a functionality where a textbox becomes disabled and changes its background color when a user unchecks a checkbox. Conversely, if the user checks the checkbox, the textbox should become editable and change its background color ...

What is the process for converting this Greasemonkey code to JavaScript specifically for Android devices?

Having trouble loading a page and running a JavaScript code on it? Don't worry, you're not alone. I came across a Greasemonkey script that does the trick, but now I'm struggling to make it work on Android. It's probably because of my la ...

What is the reason behind the label value persistently showing up after the page is refreshed?

Why is the data that I deleted from the database still showing in the label? Even after running the delete function and reloading the page. The label should not have any value once the data is deleted. Here is my code: $(document).on('click', ...

Using JQuery to make a GET request and receive a JSON response, then selecting particular objects

I am in the process of developing a straightforward web application. The concept involves users inputting a license plate number, which will then connect to an OpenData API based on Socrata that houses information about all registered vehicles in my countr ...

Effortless signing out using AJAX, Zend Framework, and jQuery

Is there a way to invoke the logout action upon a user clicking the signout link without needing a page refresh or redirecting? Any assistance would be greatly appreciated. Thank you! ...

Struggling to float <aside> to the left of <article> for proper alignment?

tldr; I'm attempting to position the aside-section to the left of the article-section (similar to a sidebar/side column), but my "float" property doesn't seem to be working at all. Is there a way to achieve this without modifying the HTML code an ...

Discover the best method for retrieving or accessing data from an array using Angular

In my data processing task, I have two sets of information. The first set serves as the header data, providing the names of the columns to be displayed. The second set is the actual data source itself. My challenge lies in selecting only the data from th ...

Deleting an added element upon closing the dialog box

Utilizing JQuery and Ajax, I successfully update my database. Following each update, a png icon is displayed briefly for 1 second. Specifically, the update form is contained within a JQuery dialog box. However, upon closing the dialog box after an update, ...

The paragraph tag closes automatically once opened

In the process of establishing a news section on my website, I encountered an issue while using the following code: <p id="news-container"> <h1> . . . </h1> <strong>big</strong> . . . </p> Upon inspecting, it appea ...

I'm looking for a way to set up a PropType that accepts a boolean value, but also allows for

Currently, my code includes a Modal component with a prop called disableEscapeKeyDown. The PropType defines it as boolean | null, but when trying to use it in the ModalWindow function, I receive an error stating Type 'boolean | null' is not assig ...

Rotating through elements in timed intervals

After exploring various examples of how to show/hide divs with a JavaScript timeout, I am still unable to resolve my specific issue. I currently have six divs that I want to cycle through sequentially every 10 seconds, starting with div #one. Although my ...

Check if a rotated rectangle lies within the circular boundary of the canvas

I have a rectangular shape that has been rotated using the ctx.rotate method, and there is also an arc on the canvas. My goal is to determine if any part of the rectangle lies within the boundaries of the arc. See the example below: https://i.sstatic.net/ ...

Enhancing AngularJS view rendering using ngshow

Currently, I am working on a view where ng-show is used to display a select DOM object when certain conditions are met, and an input DOM for all other scenarios. However, I have noticed that there is a significant delay in the disappearance of the input bo ...

Employing a "cross-domain" approach to serve as a login gateway for a different domain

I need to configure the domain: aaaa.com so that it can host a login form for the website located at domain: cccc.com. It's important to note that I have complete control over the server at cccc.com and have successfully set up CORS on that server. A ...