How to create a responsive iframe for embedding documents with HTML and CSS
If you are looking for a way to create a responsive iframe for embedding documents with HTML and CSS on your website, then this simple coding hint will be enough for you. It is true with platforms like WordPress there are plugins that can help you out with this. But what if you will like to do things with code by yourself?
An inline frame (iframe) is an HTML element that loads another HTML page within the document. It essentially puts another webpage within the parent page.
To create a responsive iframe for embedding documents, you can follow these steps:
Start by setting the width of the iframe to 100% so that it fills the entire width of its container.
Promoted contents:
- Who is the founder of BBC?
- Toshiba Corporation: Who is the founder of Toshiba?
- Google Releases Android 14 Beta 3, With Platform Stability and New Features
- Who founded Nokia? Here is all you need to know
- Who is the founder of HTC Corporation?
- Fast Charging and Multiple Variants: Samsung’s Galaxy Tab S9+ and Tab S9 Ultra Unveiled
- Who is the founder of Realme?
- The Mobvoi TicWatch 5 Pro has been launched
- Rumours of the Galaxy S23 FE: A budget-friendly variant of the Galaxy S23
- The upcoming iOS 17 will add the ability to use your locked iPhone as a smart display
<iframe src="your-document-url" width="100%"></iframe>
Next, set the iframe’s height to a fixed value, or to 0 to allow the iframe to adjust its height automatically based on the content of the embedded document.
<iframe src="your-document-url" width="100%" height="600"></iframe>
OR
<iframe src="your-document-url" width="100%" height="0"></iframe>
Now, use CSS to style the iframe’s container, making it responsive to different screen sizes. You can use media queries to adjust the width of the container at different breakpoints.
<div class="iframe-container">
<iframe src="your-document-url" width="100%" height="600"></iframe>
</div>
<style>
.iframe-container {
position: relative;
overflow: hidden;
padding-top: 56.25%; /* 16:9 aspect ratio */
}
.iframe-container iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
border: 0;
}
</style>
The CSS added to the code above will create a container with a 16:9 aspect ratio and will adjust the width of the container based on the screen size. The iframe will always fill the entire container and will adjust its height automatically based on the content of the embedded document.