0

I have an iframe embedding a pdf file but I want to ensure that the iframe extends its height automatically according to the contents in it so that the iframe scrolling bars are not shown, but every time I try the results comes unexpected here are my sample code

Here is what I tried

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Iframe</title>
<style>
    iframe{
        width: 100%;
        border: 2px solid #ccc;
    }
</style>
</head>
<body>
    <iframe src="demo.pdf" id="myIframe"></iframe>
    
    <script>
    var iframe = document.getElementById("myIframe");
 
    iframe.onload = function(){
        iframe.style.height = iframe.contentWindow.document.body.scrollHeight + 'px';
    }
    </script>
</body>
</html>

1 Answers1

0
  • Remove the height in script
  • add fit-content in css
<html lang="en">
<head>
<meta charset="utf-8">
<title>Iframe</title>
<style>
    iframe{
        height: fit-content;
        width: 100%;
        border: 2px solid #ccc;
    }
</style>
</head>
<body>
    <iframe src="demo.pdf" id="myIframe"></iframe>
    
    <script>
    var iframe = document.getElementById("myIframe");
 
    iframe.onload = function(){
    iframe.contentWindow.document.body.scrollHeight + 'px';
    }
    </script>
</body>
</html>
Johan
  • 2,088
  • 2
  • 9
  • 37
  • Please restrain from posting code only answers without any further explanation (or only diffing). A comment to the best fitting - in your opinion - existing Q&A material on site might be another alternative approach to consider. It's often quicker than quickly copy&pasting in some code and provides more context and helps building a great Q&A. – hakre Dec 09 '22 at 07:54
  • As you can see, I provided text that is not code. – Johan Dec 09 '22 at 07:54
  • Yes, you highlighted the difference, but IMHO this is not explaining much. It does add some text, that's true thought. At the end of the day, you have to judge your own answer, not me. That was only my comment (and started early without the edit). You can also reference existing Q&A by placing a link in your answer and then the question will highlight that on-site-reference prominently as well in the side-bar. – hakre Dec 09 '22 at 07:59