CSS Center an iFrame Horizontally and Vertically

What?
So this is a quick article to demo how to center an iframe horizontally and vertically in a screen/viewport in pure CSS (no JavaScript allowed). This CSS centers it by its center point rather than the top/bottom/left/right outline.

Why?
On a mobile, a client's site uses an external page embedded by iframe. When the app within the iframe has an alert message, it popups a div at the centre of its app. The alert message is always at the center of the iframe but if the iframe has a height of 2000 pixels, the iframe gets aligned to the top of the parent...

How?
We're going to use a touch of CSS and instead of determining heights and alignment with JS. The following code will work with DIV layers but in this case, also works on iframes:

HTML:
copyraw
<html>
    <head>
        <title>Horizontally and Vertically Centered Iframe</title>
    </head>
    <body>
        <iframe src="https://www.joellipman.com/examples/html/modal.html" width="350" height="2000"></iframe>
    </body>
</html>
  1.  <html> 
  2.      <head> 
  3.          <title>Horizontally and Vertically Centered Iframe</title> 
  4.      </head> 
  5.      <body> 
  6.          <iframe src="https://www.joellipman.com/examples/html/modal.html" width="350" height="2000"></iframe> 
  7.      </body> 
  8.  </html> 

CSS:
copyraw
body { 
    background:red;
}
iframe {
    position: fixed;
    top: 50%;
    left:50%;
    transform: translate(-50%, -50%); 
}
  1.  body { 
  2.      background:red; 
  3.  } 
  4.  iframe { 
  5.      position: fixed; 
  6.      top: 50%; 
  7.      left:50%; 
  8.      transform: translate(-50%, -50%)
  9.  } 

DEMO:
See my JSFiddle demo: https://jsfiddle.net/Jlipman/u5sew3ob/21
and modify the height of the iframe then click on 'Run'. The iframe is always centered even if the top is off screen.
Centered Modal where Iframe height is 200 pixels
Centered Modal where Iframe height is 450 pixels
Category: Cascading Stylesheets :: Article: 694

Add comment

Your rating:

Submit

Credit where Credit is Due:


Feel free to copy, redistribute and share this information. All that we ask is that you attribute credit and possibly even a link back to this website as it really helps in our search engine rankings.

Disclaimer: Please note that the information provided on this website is intended for informational purposes only and does not represent a warranty. The opinions expressed are those of the author only. We recommend testing any solutions in a development environment before implementing them in production. The articles are based on our good faith efforts and were current at the time of writing, reflecting our practical experience in a commercial setting.

Thank you for visiting and, as always, we hope this website was of some use to you!

Kind Regards,

Joel Lipman
www.joellipman.com

Please publish modules in offcanvas position.