Make a <div> square when there is a dynamically changing width based on percentage

Nate picture Nate · Apr 15, 2010 · Viewed 44k times · Source

I am working on a web app that will generate an NxN grid based on the user's selection of N. I want the total width of the grid to be relative (ie 100% of the available space) so that users can print on various paper sizes.

I can easily calculate the width of the squares in the grid by % (ie: 100%/N), but I am having issues calculating the height. The height of a web page is always going to be infinite unless I artificially limit it which, like I said, I don't want to do.

How can I make the squares in my grid be square versus rectangular when the height and width constraints of my grid are dynamic and not square?

Answer

web-tiki picture web-tiki · May 13, 2014

There are 2 main techniques to keep the aspect ratio of a responsive element, using padding and vw units :
(for a complete solution for a responsive grid of squares, you can see this answer)

Using vw units

You can use vw units to make your elements square and responsive (viewport units on MDN).
1vw = 1% of viewport width so you can set the height of the elements according to the width of the viewport (or height with vh units).
Example with a 4x4 grid :

body{
  margin:0;
  display:flex;
  flex-wrap:wrap;
  justify-content:space-around;
}

div{
    width:23vw; height:23vw;
    margin:1vw 0;
    background:gold;  
}
<div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>

The same behaviour can be achieved sizing the element accoring to the viewport height usin vh units.


Using padding

Padding is calculated according to the containers width so you can use it to set the height of block according to it's width.
Example with a 4x4 grid :

.wrap {
    width:80%;
    margin:0 auto;
}
.wrap div {
    width:23%;
    padding-bottom:23%;
    margin:1%;
    float:left;
    background:gold;
}
<div class="wrap">
    <div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>
</div>