How do you embed HTML into HTML (and automatically resize)?
I tried using the Inline Frame element (iframe) tag; but the iframe remains the default size—because of the default height and width settings. Further, I tried manipulating the object-fit attribute; but again the iframe remains the same default size.
I know I can manually set the height and width attributes; but I like the way other HTML elements automatically resize and I want my iframe to "insert HTML; but then sorta get out of the way and just act like other HTML"—that is, make example 2 look like example 1—see screenshot.
Note: I don’t need to use iframe; but I tried using iframe since the HTML Tag W3 Schools page suggested to do so.
For reference, I included my two index.html and note.html local files and a screenshot.
-
index.html
<html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style type="text/css"> table, th, td { border: 1px solid black; text-align: left; } </style> <title>iframe experiment</title> </head> <body> <h3>Example 1: Duplicated note</h3> <p>In the following example I duplicate my note 3 times. Notice how the HTML sizes as expected.</p> <p>Consider the following note:</p> <p>Note: This is a note.</p> <p>Consider the same note in a list:</p> <ol> <li><p>Note: This is a note.</p></li> </ol> <p>Consider the same note in a table:</p> <table> <tr> <th>Notes</th> </tr> <tr> <td><p>Note: This is a note.</p></td> </tr> </table> <h3>Example 2: Inline frame note</h3> <p>In the following example I embed my note 3 times with the <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe"><em>Inline Frame element (iframe)</em></a>. Notice how the inline frame looks wonky because of the default height and width.</p> <p>Consider the following note:</p> <iframe src="note.html"></iframe> <p>Consider the same note in a list:</p> <ol> <li><iframe src="note.html"></iframe></li> </ol> <p>Consider the same note in a table:</p> <table> <tr> <th>Notes</th> </tr> <tr> <td><iframe src="note.html" style="object-fit:none;"></iframe></td> </tr> </table> </body> </html>
-
note.html
<p>Note: This is a note.</p>
-
Screenshot
2
Answers
Two options.
An
iframe
in HTML document 1 lets you include HTML document 2 using just its URL, but the size of theiframe
is determined by document 1, not document 2. You can work around this using the Javascript trickery described in the article linked by @SteffenAndreasKloster in the comments.Another method would be to write some Javascript in document 1 to fetch the contents of document 2 as a string and then use insertAdjacentHTML() to insert that into document 1. This effectively merges document 2 into document 1 so it “will just act like other HTML”.
I hope this helps