iFrame and "max-height"
Any ideas for using max-height
on a borderless/scrolless iFrame so if it ends up being too tall the browser doesn't render a giant black area to fill开发者_Python百科 in the rest of the iFrame?
I've tried setting height="100%"
and max-height="xx"
but that doesn't seem to work.
Many Thanks!
Your use of height="100%"
, using the =
operator, suggests you're trying to use in-line attributes. This can work, but usually works better with absolute measurements (so 700px
rather than a percentage). max-height
isn't a valid attribute, so far as I'm aware, of any element except in stylesheets, so I'd suggest that you use CSS:
iframe {
min-height: 200px; /* or whatever */
max-height: 500px; /* or whatever */
}
You can, if you must, also use in-line styles, which would yield <iframe src="..." style="min-height: 200px; max-height: 500px;">
Also, while you can use percentages, to give max-height: 80%
, this does seem to require that the parent element has a defined height
of its own (I'm not sure if it's all browsers, or just one or two, but either way it seems a reasonable expectation in order that the browser can work out what 80% actually is).
A good JavaScript based answer seems to be the first solution from:
https://www.geeksforgeeks.org/how-to-adjust-the-width-and-height-of-iframe-to-fit-with-content-in-it/
Resizes the iframe to suit the content. I've found that you have to manually add a bit extra for height... go figure, but seems to work.
Here's the full mark-up and JS that works for me based on that solution:
<iframe src="/app/index.html" style="width:100%;" frameborder="0" id="Iframe">
Oops, your browser doesn't get Iframes. Click <a href="/app/index.html">Here</a> to proceed.
</iframe>
<script>
// Adjust the iframe height to exactly as much as required by the content
var frame = document.getElementById("Iframe");
frame.onload = function() {
// add extra 50 pixels - in reality need just a bit more
frame.style.height = (50+frame.contentWindow.document.body.scrollHeight) + 'px';
// not sure if this is really required.
// set the width of the iframe as the width of the iframe content
frame.style.width = frame.contentWindow.document.body.scrollWidth+'px';
}
</script>
精彩评论