Paul Randall
Paul Randall

Reputation: 133

Making divs fill up a containing div?

I've been searching the site for an answer, and nothing I've come across seems to help. I'm trying to make it so that a default (and eventually user-specified) number of divs fill up the containing div like a grid. I'm trying to figure out how to make the size of the boxes I append to the parent change depending on how many are added, while always filling up the div, if that makes sense. So for instance, if I specify 9, I should have 3 rows and 3 columns. If I specify 62, then I'm looking for 16 rows and 16 columns, always filling up (or coming close to, anyway) the containing div. Here's a JSfiddle I have so far: https://jsfiddle.net/psyonix/1g9p59bx/1/ Here's the code as it is:

    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);

});

Upvotes: 1

Views: 79

Answers (2)

Burdock
Burdock

Reputation: 1105

The only issue you had was setting the square size to 1/64th of the height instead of 1/(64^.5) of the height. Essentially you where just making one row. 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);

});

Upvotes: 1

Fuzzyma
Fuzzyma

Reputation: 8474

I would create a little jqueryplugin for that. You can call it in every container you like: containerForGrid.createGrid(cols, rows)

(function($){

$.fn.createGrid = function(cols, rows) {
  
  // get width and height of sorrounding container
  var w = this.width()
  var h = this.height()
  
  // calculate width and height of one cell
  var colWidth = w / cols
  var rowHeight = h / rows
  
  // loop over all rows
  for(var i = rows; --i;){
  
      // loop over all cols
      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>

Upvotes: 1

Related Questions