Keep an element’s aspect ratio using only CSS

This class allows us to insert a block that grows or shrinks proportionately in relation with the width of its parent container. It stays proportionately sized based on a specific aspect ratio, 1:14:316:9 – so far these are the only aspect ratios available by default but it is very easy to add your own.

To use this class simply append the aspect the ratio you would like to set replacing the colon with a dash – i.e. premise-aspect-ratio-4-3 to set the aspect ratio 4:3. You must assign this class to the wrapper or your element. By default this class assumes that your element is within a div, if it is not, then you must also assign the class premise-aspect-ratio-el to your element for this class to work properly.

Aspect Ratio Classes
class Ratio
premise-aspect-ratio (default) 16:9
premise-aspect-ratio-16-9 16:9
premise-aspect-ratio-4-3 4:3
premise-aspect-ratio-1-1 1:1

How it works

This class makes use of padding-top to set the aspect ratio for our element. The top padding of an element is calculated based on its parent’s width. So if we apply a padding-top: 10% to an element we are basically setting the padding-top to 10% of the width of said element’s parent. In other words, if I have a div container that has a width of 500px and I insert an element with padding-top: 10% into that container, my element’s height will be 50px – 500px * 10% = 50px.

To explain how we calculate the aspect ratio of an element lets use the aspect ratio 16:9 as an example and let’s see what happens when we apply the class premise-aspect-ratio-16-9 to an element’s wrapper.

first, the code
<div id="my_container" style="max-width: 500px; margin:0 auto;">
	<div class="premise-aspect-ratio-16-9">
		<div style="background-color: #4677bb;">Your content goes here</div>
	</div>
</div>

As you can see we set #my_container to have a max-width of 500px and to be centered. Our element will hold its aspect ratio within the 500px container.

Here is the results:

Aspect Ratio 16:9

 

Resize your window and watch the blue square above resize proportionately.

Send us your comments..

Your email address will not be published. Required fields are marked *