How to Set iframe Size in HTML: Width and Height Explained
To set the size of an
iframe in HTML, use the width and height attributes directly inside the <iframe> tag or apply CSS styles with width and height. Both methods control how wide and tall the iframe appears on the page.Syntax
The <iframe> tag accepts width and height attributes to set its size in pixels or percentage. Alternatively, CSS styles can be used for more flexible sizing.
- width: sets the iframe's width (e.g.,
600or100%). - height: sets the iframe's height (e.g.,
400or50vh).
html
<iframe src="URL" width="WIDTH" height="HEIGHT"></iframe>
Example
This example shows an iframe sized to 600 pixels wide and 400 pixels tall using attributes. It loads example.com inside the frame.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Iframe Size Example</title> </head> <body> <iframe src="https://example.com" width="600" height="400" title="Example Site"></iframe> </body> </html>
Output
A rectangular box 600 pixels wide and 400 pixels tall showing the example.com webpage inside it.
Common Pitfalls
Common mistakes when setting iframe size include:
- Using only
widthorheightwithout the other, causing unexpected layout. - Setting sizes without units in CSS (e.g.,
width: 600;instead ofwidth: 600px;). - Using very small sizes that make the iframe content hard to see.
- Not adding a
titleattribute for accessibility.
html
<!-- Wrong: missing units in CSS -->
<style>
iframe {
width: 600; /* Incorrect, missing 'px' */
height: 400px;
}
</style>
<!-- Correct: units included -->
<style>
iframe {
width: 600px;
height: 400px;
}
</style>Quick Reference
| Property | Description | Example |
|---|---|---|
| width (attribute) | Sets iframe width in pixels or % | |
| height (attribute) | Sets iframe height in pixels or % | |
| width (CSS) | Sets width with units like px, %, vw | iframe { width: 80%; } |
| height (CSS) | Sets height with units like px, %, vh | iframe { height: 50vh; } |
| title (attribute) | Improves accessibility by naming iframe |
Key Takeaways
Use width and height attributes on the iframe tag to set size in pixels or percentages.
CSS styles offer flexible sizing with units like px, %, vh, and vw.
Always include both width and height to avoid layout issues.
Remember to add a title attribute for accessibility.
Specify units in CSS to ensure the size is applied correctly.