Make Iframe Automatically Adjust Height According To The Contents ...
Có thể bạn quan tâm
-
- Home
- Questions
- Tags
- Users
- Companies
- Labs
- Jobs
- Discussions
- Collectives
-
Communities for your favorite technologies. Explore all Collectives
- Teams
Ask questions, find answers and collaborate at work with Stack Overflow for Teams.
Try Teams for free Explore Teams - Teams
-
Ask questions, find answers and collaborate at work with Stack Overflow for Teams. Explore Teams
Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about CollectivesTeams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about TeamsGet early access and see previews of new features.
Learn more about Labs Make iframe automatically adjust height according to the contents without using scrollbar? [duplicate] Ask Question Asked 12 years, 9 months ago Modified 4 days ago Viewed 1.6m times 669 This question already has answers here: Adjust width and height of iframe to fit with content in it (34 answers) Closed 8 years ago.For example:
<iframe name="Stack" src="http://stackoverflow.com/" width="740" frameborder="0" scrolling="no" id="iframe"> ... </iframe>I want it to be able to adjust its height according to the contents inside it, without using scroll.
Share Improve this question Follow edited Oct 3, 2020 at 13:45 David Bradshaw 13k3 gold badges44 silver badges74 bronze badges asked Apr 2, 2012 at 11:45 akashbcakashbc 6,7053 gold badges15 silver badges4 bronze badges 4- 2 This can be done via CSS there is a concept in css called media queries where content is resized according to the screen size – Vivek Khandelwal Commented Apr 2, 2016 at 7:20
- 1 Angular iFrame Auto-Height: gitlab.com/reduardo7/angular-iframe-auto-height – Eduardo Cuomo Commented Oct 3, 2016 at 14:51
- 5 "Angular…" i.e., Javascript required? In other words, one cannot do this on cross-site iframes (due to cross-site scripting restrictions), is that right? As @clankill3r is suggesting, this demonstrates the need for a pure CSS solution to this problem! – Matthew Slyman Commented Jan 5, 2017 at 20:38
- Can be done with a lib: github.com/Lemick/open-iframe-resizer – Mickaël B. Commented Aug 17 at 10:16
16 Answers
Sorted by: Reset to default Highest score (default) Trending (recent votes count more) Date modified (newest first) Date created (oldest first) 816Add this to your <head> section:
<script> function resizeIframe(obj) { obj.style.height = obj.contentWindow.document.documentElement.scrollHeight + 'px'; } </script>And change your iframe to this:
<iframe src="..." style="border-style: none; height: 0; overflow: hidden" onload="resizeIframe(this)" />As found on sitepoint discussion.
Share Improve this answer Follow edited Dec 24 at 23:16 Inigo 14.7k5 gold badges49 silver badges80 bronze badges answered Apr 2, 2012 at 12:20 hjpotter92hjpotter92 80.6k36 gold badges147 silver badges187 bronze badges 31- 381 This will not work if the iframe contains content from another domain because of the Same Origin Policy, there is another Question on SO with some cross domain solutions stackoverflow.com/questions/5589756/… – Jako Commented Mar 27, 2013 at 12:13
- 26 The solutions seems not to work if the content of the iframe has a change of height by js (e.g a slider) – shababhsiddique Commented Oct 20, 2013 at 4:59
- 26 should be onload="resizeIframe(this);" :) – rationalboss Commented Dec 20, 2013 at 12:40
- 28 Their are a few other issues you need to consider, content changing in the iframe, the browser being resized, the iframe not being full loaded when you first check it and cross domain. I put together a little library, because I couldn't find a solution that covered every issue. github.com/davidjbradshaw/iframe-resizer – David Bradshaw Commented Mar 23, 2014 at 13:17
- 4 Might be worth changing scrolling to auto in case the iframe's contents increase in height after being loaded. – rybo111 Commented Nov 29, 2015 at 17:03
You can use this library, which both initially sizes your iframe correctly and also keeps it at the right size by detecting whenever the size of the iframe's content changes. It will automatically workout the best way to calculate the page size and has an API that works around other common iframe issues.
https://iframe-resizer.com
Their are also versions for React, Vue, Angular and jQuery.
Supports both internal (same-domain) and external (cross-domain) iframes via a simple JS file that is designed to be a zero impact guest on the sites hosting it.
Share Improve this answer Follow edited Sep 11 at 17:06 answered Feb 2, 2014 at 20:52 David BradshawDavid Bradshaw 13k3 gold badges44 silver badges74 bronze badges 11- 7 This is by far the most robust solution. – hashtriplezero Commented Mar 15, 2018 at 0:41
- 22 note: when using for cross domain, requires you to be able to inject a js file into the iframe... Doesn't seem like a viable option when you don't control the iframe source. – Kyle Baker Commented Mar 28, 2018 at 6:00
- 2 @RickardElimää would be happy to take a PR to fix vh. – David Bradshaw Commented Dec 1, 2019 at 18:49
- 1 @MattWeiler in that case you can still just monkey patch the JS file into the other apps, you don't need to change any of their code and including that file won't have any negative effect on your old apps – David Bradshaw Commented May 7, 2021 at 9:28
- 2 @DavidBradshaw I'm trying to reconcile what you just wrote about monkey-patching with this comment from your project's repo: "If the other page is on a domain outside your control and you can not add JavaScript to that page, then now is the time to give up all hope of ever getting the iframe to size to the content. As it is impossible to work out the size of the contained page, without using JavaScript on both the parent and child pages." So if you don't control the external iframe domain, your library cannot work, correct? – Joel Wigton Commented Mar 28, 2022 at 16:49
Here is a compact version:
<iframe src="hello.html" sandbox="allow-same-origin" onload="this.style.height=(this.contentWindow.document.body.scrollHeight+20)+'px';"> </iframe> Share Improve this answer Follow edited May 9, 2021 at 22:31 answered Aug 23, 2015 at 2:01 Chong Lip PhangChong Lip Phang 9,2596 gold badges75 silver badges114 bronze badges 8- 3 I haven't tried this with other browsers, but I needed to add 10px with Chrome or else a vertical scrollbar showed up. I did this.style.height=(this.contentDocument.body.scrollHeight + 15) + 'px'; just to make sure it looks ok. – Mike Commented Oct 9, 2015 at 4:43
- 1 it should be onload="this.style.height = this.contentWindow.document.body.scrollHeight + 'px';" – YugoAmaryl Commented Dec 25, 2018 at 9:17
- 14 not working.. getting Blocked a frame with origin "{url}" from accessing a cross-origin frame. – Arjun Arora Commented Oct 7, 2019 at 8:53
- 1 works fine for me. – sailfish009 Commented Jun 5, 2020 at 2:28
- 2 not working here too on firefox – Digao Commented Aug 25, 2021 at 23:12
The suggestion by hjpotter92 does not work in safari! I have made a small adjustment to the script so it now works in Safari as well.
Only change made is resetting height to 0 on every load in order to enable some browsers to decrease height.
Add this to <head> tag:
<script type="text/javascript"> function resizeIframe(obj){ obj.style.height = 0; obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px'; } </script>And add the following onload attribute to your iframe, like so
<iframe onload='resizeIframe(this)'></iframe> Share Improve this answer Follow edited Nov 29, 2015 at 17:26 rybo111 12.6k4 gold badges64 silver badges73 bronze badges answered Dec 21, 2013 at 18:30 Allan PAllan P 5274 silver badges2 bronze badges 8- This also does not work if the iframe contents come from srcdoc attribute. The height will be set wrong. – Myforwik Commented Jul 14, 2014 at 1:04
- Setting height to zero first is not only for IE. – aceofspades Commented Sep 6, 2014 at 16:46
- 2 Thanks, this probably should have been a comment/suggestion to hjpotter's post mind... – ᴍᴀᴛᴛ ʙᴀᴋᴇʀ Commented Feb 25, 2015 at 15:38
- 4 You don't need those encapsulating {}'s – Steven Vachon Commented Mar 9, 2015 at 21:30
- 6 obj.style.height = 0; is very important row, that cause scrollHeight recalculating (otherwise, your contentWindow height will only increase). – Maxim Zhukov Commented May 17, 2016 at 16:16
Avoid inline JavaScript; you can use a class:
<iframe src="..." frameborder="0" scrolling="auto" class="iframe-full-height"></iframe>And reference it with jQuery:
$('.iframe-full-height').on('load', function(){ this.style.height=this.contentDocument.body.scrollHeight +'px'; }); Share Improve this answer Follow answered Nov 29, 2015 at 17:35 rybo111rybo111 12.6k4 gold badges64 silver badges73 bronze badges 0 Add a comment | 14The hjpotter92 answer works well enough in certain cases, but I found the iframe content often got bottom-clipped in Firefox & IE, while fine in Chrome.
The following works well for me and fixes the clipping problem. The code was found at http://www.dyn-web.com/tutorials/iframes/height/. I have made a slight modification to take the onload attribute out of the HTML. Place the following code after the <iframe> HTML and before the closing </body> tag:
<script type="text/javascript"> function getDocHeight(doc) { doc = doc || document; // stackoverflow.com/questions/1145850/ var body = doc.body, html = doc.documentElement; var height = Math.max( body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight ); return height; } function setIframeHeight(id) { var ifrm = document.getElementById(id); var doc = ifrm.contentDocument? ifrm.contentDocument: ifrm.contentWindow.document; ifrm.style.visibility = 'hidden'; ifrm.style.height = "10px"; // reset to minimal height ... // IE opt. for bing/msn needs a bit added or scrollbar appears ifrm.style.height = getDocHeight( doc ) + 4 + "px"; ifrm.style.visibility = 'visible'; } document.getElementById('ifrm').onload = function() { // Adjust the Id accordingly setIframeHeight(this.id); } </script>Your iframe HTML:
<iframe id="ifrm" src="some-iframe-content.html"></iframe>Note if you prefer to include the Javascript in the <head> of the document then you can revert to using an inline onload attribute in the iframe HTML, as in the dyn-web web page.
Share Improve this answer Follow edited Jul 4, 2015 at 12:02 answered Jul 4, 2015 at 11:01 JimadineJimadine 1,04414 silver badges26 bronze badges 2- This is the only one that worked for me. Thank you so much! – Yasser Jarouf Commented Nov 7, 2018 at 19:48
- Not working now in 2021. – WilliamK Commented Jun 10, 2022 at 21:25
jQuery's .contents() method method allows us to search through the immediate children of the element in the DOM tree.
jQuery:
$('iframe').height( $('iframe').contents().outerHeight() );Remember that the body of the page inner the iframe must have its height
CSS:
body { height: auto; overflow: auto } Share Improve this answer Follow edited Aug 24, 2016 at 14:22 answered Jan 20, 2015 at 15:54 Nathalia XavierNathalia Xavier 1,03910 silver badges14 bronze badges 4- 1 Add a demo to your answer to give it more value. – Stephan Commented Mar 22, 2015 at 15:01
- This worked for me but only when removing 'body' to make it contents() – Simon_Weaver Commented Aug 23, 2016 at 6:19
- 5 same problem as before, doesn't work cross origin – nuander Commented Jan 25, 2017 at 22:56
- 2 jQuery('iframe').height(jQuery('iframe').contents().find('body').height()); worked for me when the iframe had loaded – Michael L Watson Commented Jun 9, 2017 at 16:27
Try this:
<iframe name="Stack" src="http://stackoverflow.com/" style='height: 100%; width: 100%;' frameborder="0" scrolling="no" id="iframe">...</iframe> Share Improve this answer Follow edited Jul 7, 2023 at 12:50 András Aszódi 9,6305 gold badges52 silver badges54 bronze badges answered Dec 9, 2015 at 22:09 LuckyLucky 8012 gold badges11 silver badges31 bronze badges 5- 5 Why are you writing for one browser? Many people, with many operating systems, and many browsers will view your site. – ctrl-alt-delor Commented Jan 3, 2016 at 15:57
- 4 Works! (on Chrome, Firefox, Safari, IE) – strix25 Commented Jul 11, 2019 at 12:16
- 4 height: 100vh works better than % on my side – Marvel Moe Commented Aug 11, 2022 at 23:34
- 1 I can confirm that this works nicely. I hope @Lucky doesn't mind that I edited the contentious "...for IE11" away :-) – András Aszódi Commented Jul 7, 2023 at 12:50
- 5 This is just styling the iframe to fit 100% of its container. The OP is asking how to fit the iframe to its content -- meaning the iframe, itself, is the container. I don't think this answer actually solves the problem. People are just lucky it works some times. – Cody Commented Feb 9 at 16:35
This works for me (also with multiple iframes on one page):
$('iframe').load(function(){$(this).height($(this).contents().outerHeight());}); Share Improve this answer Follow answered May 17, 2015 at 6:57 user2992220user2992220 1,1121 gold badge12 silver badges20 bronze badges Add a comment | 2This works for me (mostly).
Put this at the bottom of your page.
<script type="application/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script> <script type="application/javascript" src="/script/jquery.browser.js"> </script> <script type="application/javascript" src="/script/jquery-iframe-auto-height.js"> </script> <script type="application/javascript"> jQuery('iframe').iframeAutoHeight(); $(window).load( function() { jQuery('iframe').iframeAutoHeight(); } ); // for when content is not html e.g. a PDF function setIframeHeight() { $('.iframe_fullHeight').each( function (i, item) { item.height = $(document).height(); } ); }; $(document).ready( function () { setIframeHeight(); }); $(window).resize( function () { setIframeHeight(); }); </script>The first half is from ???, and works when there is html in the iframe. The second half sets the iframe to page height (not content height), when iframes class is iframe_fullHeight. You can use this if the content is a PDF or other such like, but you have to set the class. Also can only be used when being full height is appropriate.
Note: for some reason, when it recalculates after window resize, it gets height wrong.
Share Improve this answer Follow edited Jan 3, 2016 at 17:02 answered Jan 3, 2016 at 16:51 ctrl-alt-delorctrl-alt-delor 7,7255 gold badges44 silver badges54 bronze badges Add a comment | 1 function autoResize(id){ var newheight; var newwidth; if(document.getElementById){ newheight=document.getElementById(id).contentWindow.document.body.scrollHeight; newwidth=document.getElementById(id).contentWindow.document.body.scrollWidth; } document.getElementById(id).height=(newheight) + "px"; document.getElementById(id).width=(newwidth) + "px"; }add this to your iframe: onload="autoResize('youriframeid')"
Share Improve this answer Follow edited Feb 9, 2015 at 16:30 Neil Thompson 6,4152 gold badges32 silver badges55 bronze badges answered Jan 15, 2014 at 19:49 SimonSimon 1,3744 gold badges14 silver badges28 bronze badges Add a comment | 1 jq2('#stocks_iframe').load(function(){ var iframe_width = jq2('#stocks_iframe').contents().outerHeight() ; jq2('#stocks_iframe').css('height',iframe_width); }); <iframe id='stocks_iframe' style='width:100%;height:0px;' frameborder='0'> Share Improve this answer Follow answered May 4, 2015 at 8:52 Айдън БейтуловАйдън Бейтулов 751 silver badge9 bronze badges Add a comment | 0I did it with AngularJS. Angular doesn't have an ng-load, but a 3rd party module was made; install with bower below, or find it here: https://github.com/andrefarzat/ng-load
Get the ngLoad directive: bower install ng-load --save
Setup your iframe:
<iframe id="CreditReportFrame" src="about:blank" frameborder="0" scrolling="no" ng-load="resizeIframe($event)" seamless></iframe>Controller resizeIframe function:
$scope.resizeIframe = function (event) { console.log("iframe loaded!"); var iframe = event.target; iframe.style.height = iframe.contentWindow.document.body.scrollHeight + 'px'; }; Share Improve this answer Follow edited Apr 5, 2015 at 23:06 Mark Amery 154k89 gold badges426 silver badges469 bronze badges answered Nov 4, 2014 at 20:55 Charles NaccioCharles Naccio 3583 silver badges6 bronze badges Add a comment | 0I wanted to make an iframe behave like a normal page (I needed to make a fullscreen banner inside an iframe element), so here is my script:
(function (window, undefined) { var frame, lastKnownFrameHeight = 0, maxFrameLoadedTries = 5, maxResizeCheckTries = 20; //Resize iframe on window resize addEvent(window, 'resize', resizeFrame); var iframeCheckInterval = window.setInterval(function () { maxFrameLoadedTries--; var frames = document.getElementsByTagName('iframe'); if (maxFrameLoadedTries == 0 || frames.length) { clearInterval(iframeCheckInterval); frame = frames[0]; addEvent(frame, 'load', resizeFrame); var resizeCheckInterval = setInterval(function () { resizeFrame(); maxResizeCheckTries--; if (maxResizeCheckTries == 0) { clearInterval(resizeCheckInterval); } }, 1000); resizeFrame(); } }, 500); function resizeFrame() { if (frame) { var frameHeight = frame.contentWindow.document.body.scrollHeight; if (frameHeight !== lastKnownFrameHeight) { lastKnownFrameHeight = frameHeight; var viewportWidth = document.documentElement.clientWidth; if (document.compatMode && document.compatMode === 'BackCompat') { viewportWidth = document.body.clientWidth; } frame.setAttribute('width', viewportWidth); frame.setAttribute('height', lastKnownFrameHeight); frame.style.width = viewportWidth + 'px'; frame.style.height = frameHeight + 'px'; } } } //-------------------------------------------------------------- // Cross-browser helpers //-------------------------------------------------------------- function addEvent(elem, event, fn) { if (elem.addEventListener) { elem.addEventListener(event, fn, false); } else { elem.attachEvent("on" + event, function () { return (fn.call(elem, window.event)); }); } } })(window);The functions are self-explanatory and have comments to further explain their purpose.
Share Improve this answer Follow edited Jul 10, 2017 at 21:56 user6152171 answered Sep 25, 2015 at 13:54 Chris PanayotoffChris Panayotoff 1,93623 silver badges25 bronze badges 3- 1 May be some need an explanation, at least how to use it. And what it does. (-1) – ctrl-alt-delor Commented Jan 3, 2016 at 16:02
- This works for me on FF, but I agree with @richard that some explanation will go some way towards getting this accepted as an answer. – crafter Commented Apr 18, 2017 at 15:08
- there is like.... 1 comment, on the obvious thing. The actual stuff i don't understand has no comments. No mention if this is affected by SOP. Worst, it uses setTimeout - imagine if i was on a really slow connection... – RozzA Commented Oct 6, 2017 at 4:01
I've had problems in the past calling iframe.onload for dynamically created iframes, so I went with this approach for setting the iframe size:
iFrame View
var height = $("body").outerHeight(); parent.SetIFrameHeight(height);Main View
SetIFrameHeight = function(height) { $("#iFrameWrapper").height(height); }(this is only going to work if both views are in the same domain)
Share Improve this answer Follow answered Feb 25, 2014 at 14:29 OwenOwen 4,3975 gold badges43 silver badges52 bronze badges 0 Add a comment | -4 <script type="text/javascript"> function resizeIframe(obj) { obj.style.height = 0; obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px'; } </script>this is not working for chrome. But working for firefox.
Share Improve this answer Follow edited Jan 18, 2017 at 16:03 henrebotha 1,2982 gold badges15 silver badges38 bronze badges answered Oct 5, 2014 at 14:59 santoshssantoshs 13 Add a comment | Highly active question. Earn 10 reputation (not counting the association bonus) in order to answer this question. The reputation requirement helps protect this question from spam and non-answer activity.Not the answer you're looking for? Browse other questions tagged
or ask your own question.- The Overflow Blog
- The ghost jobs haunting your career search
- Breaking up is hard to do: Chunking in RAG applications
- Featured on Meta
- The December 2024 Community Asks Sprint has been moved to March 2025 (and...
- Stack Overflow Jobs is expanding to more countries
Linked
441 Adjust width and height of iframe to fit with content in it -1 Make div scroll with browser scrollbar 0 how to set height of an iframe based on its content 0 Add iframe from different domain to Wordpress without scroll and 100% height 1 Angular 5 iframe set width and height same as its content 523 Resizing an iframe based on content 142 Is there a cross-domain iframe height auto-resizer that works? 49 iFrame Height Auto (CSS) 32 How to Make iframe 100% height according to its content 32 Get value of input field inside an iframe See more linked questionsRelated
2815 Make a div fill the height of the remaining screen space 2699 How to make a div 100% height of the browser window 1467 Maintain the aspect ratio of a div with CSS 1122 Make body have 100% of the browser height 859 How can I access the contents of an iframe with JavaScript/jQuery? 1 Make iframe automatically adjust height 692 CSS3 100vh not constant in mobile browser 441 Adjust width and height of iframe to fit with content in itHot Network Questions
- What's the point of putting a resistor here?
- How to determ a custom post type url?
- Did I accidentally delete files? How can I recover them?
- Why is sorting a table (loaded with random data) faster than actually sorting random data?
- Why is a program os dependent?
- Capital Gains and investing in Spain
- What color is antimatter?
- Are there convex polyhedrons with isosceles triangular faces that are also mutually non-congruent?
- Can President sign a bill passed by one Congress once a new Congress has been sworn in if the bill is delayed being presented to him (there’s a lag)?
- Mentioning owning a business on an interview
- How many ways 4 identical apples and 4 identical oranges be distributed among 6 children if each child gets at least 1 fruit?
- Does enabling FILESTREAM for file I/O access improve performance and manageability in handling file data?
- How to make machine always turn on after a power outage
- TV show where a guy finds a liquid that can bring pictures to life
- Is there a difference between V and F in German?
- Why Are Guns Called 'Biscuits' In America?
- Which is the default butter in the US?
- Why are we interested in derived category?
- Nonograms that require more than single-line logic
- Is it bad practice to state the purpose of a verification code?
- Options for wiring a switch and lights with minimal wire length
- Where was it first established that Clayface was weak to electricity?
- Symmetrically scale object along profile on a single axis
- Why the wavefunction phases change under different environments?
Từ khóa » Html Iframe Resize To Fit Content
-
How To Adjust The Width And Height Of Iframe To Fit With Content In It
-
Resize Iframe To Fit Content (Same Domain Only) - CSS-Tricks
-
Change Iframe Size Automatically To Fit Content & Prevent Scrollbars
-
Automatically Adjust IFrame Height According To Its Contents Using ...
-
How To Scale The Content Of
-
How To Fit Content In Iframe Code Example
-
Iframe Height 100 Code Example
-
How To Adjust Width And Height Of Iframe To Fit With Content In It
-
Resize External Website Content To Fit Iframe Width
-
How Do I Fit An Iframe To Its Size? - Brain Writings
-
Iframe Auto Adjust Height As Content Changes
-
Resize An Iframe To Fit Its Content - HTML DOM
-
Resize Iframe Height To Fit Content (works Cross Domain) · GitHub
-
Html – Resize Iframe Until There Is No Scrollbar(fit Content) - ITecNote