How To Maintain Height Proportionate To Width in CSS or jQuery

November 28th, 2015 - Posted by Steve Marks to (X)HTML / CSS, Javascript / jQuery, Web Development.

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 1: jQuery

HTML:

<div id="resizeMe"></div>

JavaScript:

jQuery(window).resize(function()
{
    var ratio = 3/4; // height / width
    jQuery('#resizeMe').height( jQuery('#resizeMe').width() * ratio );
});

// When the page loads, trigger a window resize event
// so our element gets resized by default. Saves having 
// to duplicate the same code on load too.
jQuery(window).load(function()
{
    jQuery(window).trigger('resize');
});

Method 2: CSS

HTML:

<div id="resizeMe">
    <div id="resizeMeInner"></div>
</div>

CSS:

#resizeMe {
	width:300px;
	border:1px solid #000;
}
#resizeMeInner {
	padding-top:75%; /* (height / width) * 100 */
}

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.

This entry was posted on Saturday, November 28th, 2015 at 11:01 am by +Steve Marks and is filed under (X)HTML / CSS, Javascript / jQuery, Web Development. You can follow any responses to this entry through the RSS 2.0 feed.
Comments...

Fear not, we won't publish this

Comments (0)

No comments have been left yet. Be the first