CSS width and height maintain ratio

CSS Maintaining Width and Height Ratio

CSS Maintaining Width and Height Ratio

In front-end development, we often encounter situations where we need to set the width and height ratio of elements to remain unchanged. For example, when designing a responsive web page, we may need to maintain a certain aspect ratio for an image or video across different screen sizes to ensure the page layout looks good and functions properly. In this case, we need to use CSS to maintain this aspect ratio.

Method 1: Using Padding

A common approach is to use padding to create a placeholder, then place content within the placeholder, controlling the aspect ratio using the percentage value of the padding. The specific implementation is as follows:


<!DOCTYPE html> 
<html lang="en"> 
<head> 
<meta charset="UTF-8"> 
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>CSS Maintaining Aspect Ratio</title>
<style>
.wrapper {
position: relative;
width: 100%;
padding-top: 56.25%; /* 16:9 video aspect ratio */
}

.content {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}

</style>

</head>

<body>
<div class="wrapper">
<div class="content">
<!-- Place content here to maintain aspect ratio -->
</div>
</div>

</body>
</html>

In this code, we maintain aspect ratio by setting the padding-top of the wrapper container .wrapper to 56.25% (i.e., a 16:9 aspect ratio), and then placing the .content container inside it. Place your content within the .content container.

Method 2: Using Absolute Positioning

Another common method to control the aspect ratio of an element is to use absolute positioning. The specific implementation is as follows:

<!DOCTYPE html> 
<html lang="en"> 
<head> 
<meta charset="UTF-8"> 
<meta name="viewport" content="width=device-width, initial-scale=1.0"> 
<title>CSS Aspect Ratio</title> 
<style> 
.wrapper { 
position: relative; 
width: 100%; 
height: 0; 
padding-top: 56.25%; /* 16:9 video aspect ratio */ 
} 

.content { 
position: absolute; 
top: 0; 
left: 0; 
width: 100%; 
height: 100%; 
} 
</style> 
</head> 
<body> 
<div class="wrapper"> 
<div class="content"> 
<!-- Place content here to maintain aspect ratio --> 
</div> 
</div> 
</body> 
</html> 

Similar to method 1, here we also use the padding-top property of the placeholder container .wrapper to achieve aspect ratio, and then use the absolutely positioned .content container to maintain the aspect ratio.

Practical Application

Next, let’s look at a practical example of how to use CSS to maintain the aspect ratio of a video in a responsive web page.

Leave a Reply

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