PatrikJ
PatrikJ

Reputation: 2398

Create iframe in the middle of the page

Long story short. I need to create an iframe with javascript and align it in the center of the page.

I found this nice piece of code:

var iframe = document.createElement('iframe');
var html = '<body>Foo</body>';
iframe.src = 'data:text/html;charset=utf-8,' + encodeURI(html);
document.body.appendChild(iframe);
console.log('iframe.contentWindow =', iframe.contentWindow);

Does anyone have an idea how to fix the alignment to be centered? The reason for choosing an iframe to begin with is because I want the frame to be independent of the current page's CSS styles.

/Patrik

Upvotes: 0

Views: 622

Answers (1)

user2755140
user2755140

Reputation: 2027

1- Get browser window size

2- Get iframe width and height

3- Substract number 2 from number 1

4- Divide rounding the resultby 2

And that way you'll have the x and y coordinates for your iframe to locate it in the center of the browser window.

Upvotes: 1

Related Questions