Maintaining Aspect Ratios for HTML Videos with CSS

CSSWeb DevelopmentFront End Technology

By specifying padding of an element in percentage, we can maintain its Aspect Ratio.

For this, use the CSS padding property −

  • The padding-bottom specifies the bottom padding of an element.

  • The padding-top specifies the top padding of an element.

  • The padding-left specifies the left padding of an element.

  • The padding-right specifies the right padding of an element.

  • The padding serves as shorthand for the preceding properties.

Example

The following examples illustrate CSS padding property to maintain aspect ratio.

 Live Demo

<!DOCTYPE html>
<html>
<head>
<style>
#demo {
   padding-top: 100%;
   box-shadow: 0 0 24px steelblue;
   position: relative;
   width: 100%;
}
div > div {
   margin: 10px;
   position: absolute;
   top: 0;
   right: 0;
   bottom: 0;
   left: 0;
   text-align: center;
}
</style>
</head>
<body>
<p>Watch the below div</p>
<div id="demo">
<div>Fun Ratio!</div>
</div>
</body>
</html>

Output

This will produce the following result −

Even after resizing the window, aspect ratio remains 1:1.

Example

 Live Demo

<!DOCTYPE html>
<html>
<head>
<style>
div {
   margin: 10%;
   padding-top: 56.25%;
   height: 0px;
   position: relative;
   box-shadow: 0 0 0 20px antiquewhite;
}
iframe {
   position: absolute;
   top: 0;
   height: 100%;
   width: 100%;
}
</style>
</head>
<body>
<div>
<iframe src="https://www.youtube.com/embed/0cwk9UMLnWE" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-inpicture" allowfullscreen></iframe>
</div>
</body>
</html>

Output

This will produce the following result −

raja
Published on 12-Mar-2021 11:18:06
Advertisements