Signup/Sign In
LAST UPDATED: AUGUST 5, 2021

How to create responsive iframes with CSS?

An iframe is used to embed another document, webpage, or videos within the HTML page. A responsive iframe is that which can be resized depending on the screen size of the device. We can create these responsive iframes using CSS.

A responsive iframe

To create a responsive iframe, use a div container to add the iframe. Set the aspect ratio of the div container using CSS padding-top and set the value of padding-top in percentage.

The aspect ratio describes the relationship between width and height. The aspect ratio can be 16:9 or 4:3, etc. The iframe will adjust according to the size of the screen keeping the aspect ratio constant.

Example: A responsive iframe using padding-top

In this example, we will create an iframe with an aspect ratio of 16:9.

<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>HTML</title>
<style>	
	.container {
	  position: relative;
	  overflow: hidden;
	  width: 100%;
	  padding-top: 56.25%; /* 16:9 Aspect Ratio  */
	}
	/*  style the iframe with full height and width */
	iframe {
	  position: absolute;
	  top: 0;
	  left: 0;
	  bottom: 0;
	  right: 0;
	  width: 100%;
	  height: 100%;
	}
</style>
</head>  
<body>
    <h2> Responsive iframes </h2>
	<div class="container">
	   <iframe src="https://www.youtube.com/embed/xoTyrdT9SZI" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
	</div>
</body>
</html>

Output

Here is the output of the above program.

Responsive iframe

Example: A responsive iframe using padding-bottom

We can also create a responsive iframe using padding-bottom property. Here, we have set the aspect ratio of 4:3 to the iframes.

Conclusion

In this tutorial, we have created a responsive iframe with CSS. We have set the percentage value to the padding-top or padding-bottom properties. The aspect ratio can vary from 16:9, 4:0, or 3:2. The aspect ratio remains the same in the all-size devices.



About the author: