CSS Proportional Resizable Boxes

In this article I will explain how to define boxes of variable size but preserve the aspect ratio (without using JavaScript). A while ago I had the need to create a grid with multiple square boxes tha

CSS Proportional Resizable Boxes

In this article I will explain how to define boxes of variable size but preserve the aspect ratio (without using JavaScript). A while ago I had the need to create a grid with multiple square boxes that suit different resolutions. The first option that came to mind was to use percentages to define the width of the boxes and then use JavaScript to apply the same value to the height. A few months later, reading about CSS units came to my mind that project and a better solution to build the grid using only HTML and CSS. To start we need to know the basic aspects of the units that will use.


CSS Units

We can categorize CSS units into two groups:

Absolute units

Are fixed and -mostly- relate to some physical measurement. Once they are declared, their size cannot be altered by changing the font size of some other element.

px - 1 “viewport pixel”  
pt - 1 point is 1/72 of an inch  
pc - 1 pica is equal to 12 points  
Relative units

Do not have an objective measurement. Instead, their actual size is determined by the size of a parent element. This means that their size can be altered by changing the sizing of that dependent element.

% - Relative to the parent element’s font size
em - Relative to the parent element’s font size  
rem - (root em) Relative to the html font size  
keyword - xx-small, x-small, small, medium, large, x-large, xx-large  
vw - 1/100th of the width of the viewport  
vh - 1/100th of the height of the viewport  
vmin - 1/100th of the viewport’s smaller dimension (height or width)  
vmax - 1/100th of the viewport’s larger dimension (height or width)  

You can see an exhaustive list of units here, but we'll focus on the two first viewport units (vw, vh), as they are more likely to be used. The vw unit, uses the viewport width to calculate the size, this allows for a more fluid responsive sizing.


Resizable Squares

Now we can just use the viewport units to apply proportional sizes to one box using the same unit in both width and height, for example width: 25vw; and height: 25vw;.

Here's an example of a grid using 25vw box sizes.

See the Pen CSS Proportional Resizable Boxes by Guillermo Cura (@guillecura) on CodePen.

So, using viewport units you can create a responsive-scalable grid like this:

See the Pen CSS Proportional Scalable Grid by Guillermo Cura (@guillecura) on CodePen.


Browser Support

The viewport units are CSS3 units and some browsers have partial support but using vw and vh shouldn't cause any trouble. Anyway, you can check the full "supported browser list" here!