How To Maintain Height Proportionate To Width in CSS or jQuery

There are a lot of times when we find ourselves having to ensure elements retain their proportionality, regardless of the screen size. This might be ensuring an image used as a background image is kept at the correct ratio, or ensuring an element remains exactly square.

There are two methods we use to assist with this; one using jQuery and the other using CSS. We’ll explain both here:

Note: In the examples below we’ll be ensuring that the element in question remains at a ratio of 4:3.

Method 2: CSS

With the CSS method above, the padding top applied is a percentage of the parent’s width. So the parent has a width of 300px, therefore with a padding top of 75% the height of the element comes out at 225px. If we had no outer element the div would be set to a height which is equal to 75% of the window height.

For the above two methods, if the div being resized contains a background image, it might be worth adding the following CSS to ensure that, should an image be used that isn’t of the correct ratio, it still fills the available area:

background-size:cover

Using one of the two methods above, your elements can now always remmain in proportion, regardless of the users resolution or the device being used.