HTML Iframe
An iframe (Inline Frame) is used to embed content from another website into an HTML page.
Iframe Tag
<iframe src="https://www.google.com/maps" width="600" height="400"></iframe>
Iframe Attributes
src
<iframe src="page.html"></iframe>
width and height
<iframe src="page.html" width="600" height="400"></iframe>
frameborder
<iframe src="page.html" frameborder="0"></iframe>
allowfullscreen
<iframe src="video.html" allowfullscreen></iframe>
name
<iframe src="page.html" name="myframe"></iframe>
<a href="link.html" target="myframe">Open in iframe</a>
Case Study: Campus Location Map
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Campus Location</title>
<style>
.map-container {
width: 100%;
max-width: 800px;
margin: 0 auto;
}
.map-container iframe {
width: 100%;
height: 400px;
border: 1px solid #e5e7eb;
border-radius: 8px;
}
</style>
</head>
<body>
<h1>Technology University Location</h1>
<div class="map-container">
<iframe
src="https://www.google.com/maps/embed?pb=!1m18!..."
width="600"
height="400"
style="border:0;"
allowfullscreen=""
loading="lazy"
title="Campus Location Map">
</iframe>
</div>
<div>
<h2>Address</h2>
<p>123 Technology Street<br>Chicago, 12345</p>
</div>
</body>
</html>
Everyday Case Study
Case: A developer needs to embed a YouTube video.
<h2>Campus Profile Video</h2>
<div class="video-container">
<iframe
width="560"
height="315"
src="https://www.youtube.com/embed/VIDEO_ID"
title="Campus Profile Video"
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen>
</iframe>
</div>
Iframe Sandbox
<iframe
src="https://example.com"
sandbox="allow-same-origin allow-scripts"
title="Sandboxed iframe">
</iframe>
Sandbox Permissions
allow-same-origin: Allow same originallow-scripts: Allow scriptsallow-forms: Allow formsallow-popups: Allow popups
Responsive Iframe
<style>
.responsive-iframe {
position: relative;
padding-bottom: 56.25%;
height: 0;
overflow: hidden;
}
.responsive-iframe iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
</style>
<div class="responsive-iframe">
<iframe src="video.html" frameborder="0" allowfullscreen></iframe>
</div>
Best Practices
- Title attribute: For accessibility
- Sandbox: For security
- Lazy loading: For performance
- Responsive: Use CSS for responsiveness
- Alternatives: Consider other options
Summary
Iframes embed external content. Use them wisely and consider both security and performance.