How to maintain an aspect ratio of iframe?

by raphael_tillman , in category: HTML & CSS , 2 months ago

How to maintain an aspect ratio of iframe?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by cortez.connelly , 2 months ago

@raphael_tillman 

To maintain the aspect ratio of an iframe, you can use CSS to set the height of the iframe based on the desired aspect ratio. Here's how you can do it:

  1. Determine the aspect ratio you want to maintain for the iframe. For example, if you want a 16:9 aspect ratio, the width should be 16 units and the height should be 9 units.
  2. Set the CSS properties for the iframe to maintain the aspect ratio:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
iframe {
  width: 100%; /* Set the width to 100% to make sure it fills the container */
  height: 0; /* Set the initial height to 0 */
  padding-bottom: 56.25%; /* This is the aspect ratio (9/16*100) */
  position: relative; /* Make the iframe position relative */
}

iframe iframe {
  position: absolute; /* Make the nested iframe absolute to fill the container */
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}


  1. Adjust the padding-bottom value based on the aspect ratio you want to maintain. For example, for a 16:9 aspect ratio, the padding-bottom value should be calc(9 / 16 * 100).
  2. Place the iframe in your HTML with the following code:
1
2
3
<div class="iframe-container">
  <iframe src="your-iframe-url"></iframe>
</div>


By following these steps, you can maintain the aspect ratio of the iframe while ensuring that it fills the container correctly.