How to Make iframe Responsive in CSS: Simple Steps
iframe responsive in CSS, wrap it in a container with position: relative; and use padding-top to keep the aspect ratio. Then set the iframe to position: absolute;, width: 100%;, and height: 100%; so it fills the container and scales with the screen size.Syntax
Wrap the iframe inside a container div. The container uses position: relative; and a padding-top value to keep the aspect ratio (like 56.25% for 16:9). The iframe inside uses position: absolute;, top: 0;, left: 0;, width: 100%;, and height: 100%; to fill the container fully and resize responsively.
<div class="iframe-container"> <iframe src="URL" frameborder="0" allowfullscreen title="Responsive iframe"></iframe> </div> <style> .iframe-container { position: relative; width: 100%; padding-top: 56.25%; /* 16:9 Aspect Ratio */ } .iframe-container iframe { position: absolute; top: 0; left: 0; width: 100%; height: 100%; border: 0; } </style>
Example
This example shows a responsive YouTube video embedded with an iframe. The video scales to fit the width of the screen while keeping the correct height ratio.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Responsive iframe Example</title> <style> .iframe-container { position: relative; width: 100%; max-width: 600px; margin: auto; padding-top: 56.25%; /* 16:9 Aspect Ratio */ } .iframe-container iframe { position: absolute; top: 0; left: 0; width: 100%; height: 100%; border: 0; } </style> </head> <body> <h2 style="text-align:center;">Responsive YouTube Video</h2> <div class="iframe-container"> <iframe src="https://www.youtube.com/embed/dQw4w9WgXcQ" allowfullscreen title="YouTube video"></iframe> </div> </body> </html>
Common Pitfalls
Common mistakes include setting fixed width and height on the iframe directly, which breaks responsiveness. Another error is forgetting to set the container's position to relative, which causes the iframe's absolute positioning to fail.
Also, not using the correct padding-top percentage for the aspect ratio will distort the iframe content.
<!-- Wrong way: fixed size iframe --> <iframe src="URL" width="560" height="315"></iframe> <!-- Right way: responsive container --> <div style="position: relative; width: 100%; padding-top: 56.25%;"> <iframe src="URL" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; border: 0;" allowfullscreen title="Responsive iframe"></iframe> </div>
Quick Reference
- Container:
position: relative;,width: 100%;,padding-topfor aspect ratio. - iframe:
position: absolute;,top: 0;,left: 0;,width: 100%;,height: 100%;,border: 0;. - Use
padding-top= (height / width) * 100% for correct aspect ratio. - Always include
allowfullscreenandtitlefor accessibility.