Signup/Sign In

How to maintain aspect ratio of element with CSS?

Aspect ratio is the ratio between the width and height of an element in the webpage. The aspect ratio will help the element to adjust itself in different screen sizes. For example, if you are taking an image of 1:1 then it will remain the same whether it is a small screen or a bigger screen. Let's learn to maintain this aspect ratio with CSS.

Maintaining aspect ratio with CSS

Use CSS padding-top or padding-bottom property to maintain the aspect ratio of elements in the webpage. The values for the padding-top or padding-bottom will be defined in percentage. For example, padding-top: 100% will define an element with a 1:1 aspect ratio.

Example: Creating a container with a 1:1 aspect ratio

In this example, we have created a div container with an aspect ratio of 1:1. We have used padding-bottom: 100% for it.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HTML</title>
<style>
   .container {
      padding-bottom: 100%;
	  background-color: #ccc;
	  width: 100%;
   }   
</style>
</head>
<body>
   <h2> Maintaining aspect ratio of div element </h2>
   <div class="container">
	</div>
</body>
</html>

Output:

Here is the output of the above example.

maintaining aspect ratio of 1:1

Example: A div maintaining the aspect ratio of 16:4

In the next example, we have used padding-top: 56.25% to create a div container with an aspect ratio of 16:4.

Conclusion

We can use either padding-top or padding-bottom to preserve the aspect ratio of a div element. Also, add the values accordingly to set a particular aspect ratio. CSS made it quick and easy to maintain the aspect ratio.



About the author: