1

What's the best way to center an iframe?

Do you foresee any issues with something simple like this?

<html>
<body>

<iframe src="https://abc.123.com/" width="100%" height="100%"></iframe>



</body>
</html>
Ray
  • 3,409
  • 8
  • 33
  • 40

3 Answers3

1

Here's my take:

<html>
<body>

<iframe src="https://abc.123.com/" style="border: none; width: 100%; height: 100%">Your browser doesn't support iFrames.</iframe>

</body>
</html>

You'll need this CSS to ensure 100% height and width, as well as no margins or padding.

body, html {
    padding: 0;
    margin: 0;
    height: 100%;
    width: 100%;
}

http://jsfiddle.net/PAmDU/

Keep in mind that this may cause disdain from users who find inconsistencies with the back/forward button changing the whole page rather than the iframe covering the whole page. If possible, it's best to avoid using iframes for something like this, if at all these days.

Aram Kocharyan
  • 20,165
  • 11
  • 81
  • 96
  • Thanks a ton, Aram. Why are iFrames so looked down upon these days? Do you have a external link that I can read about this topic? – Ray Feb 02 '12 at 04:31
  • This won't center the iframe if the iframe is anything other than 100% width. Also, it leaves scroll bars due to the border on the iframe. – Jason Feb 02 '12 at 04:35
  • I was under the impression the user wanted the whole thing to cover the screen, from their question. But you're right, the title did say centered. See http://jsfiddle.net/tDLkr/3/ – Aram Kocharyan Feb 02 '12 at 04:46
0
<iframe src="https://abc.123.com/" style="border: 0; width: 100%; height: 100%">Your browser doesn't support iFrames.</iframe>

That would work just fine, however you still will have a very tiny grey border on it.

To fix that, use this in the CSS:

body {
    margin: 0;
}
ionFish
  • 1,004
  • 1
  • 8
  • 20
0

If you truly want it centered and a width of anything but 100%, use something like this:

<html>
<body style="margin: 0;">
    <div style="margin: 0 auto; width: 500px;"><!--Change this width if you want-->
        <iframe src="http://www.w3schools.com" style="width: 100%; height: 100%; border: none;">
        </iframe>
    </div>
</body>
</html>

I also got rid of the iframe border which causes scroll bars.

Jason
  • 11,435
  • 24
  • 77
  • 131