Max Schmitt

February 28 2023

Building a Responsive Website Tester with Iframes and React

In this post, I will show you how to build a simple responsive website tester using the "scaling iframe" technique.

Responsive Iframe vs. Scaling Iframe

If you use an <iframe> with width: 100%;, the content of the iframe behaves responsively and is dependent on the available space:

Responsive Iframe

If you want to show the iframe's content at a specific breakpoint instead, no matter the available space, you can use a scaling iframe:

Scaling Iframe

This is what we'll use for our responsive website tester.

Building a Scaling Iframe

This "scaling iframe" requires a bit of JavaScript. The general strategy is simple:

1. Give the Iframe a Fixed Width

The <iframe> element will have a fixed width, the same as the breakpoint we want the website to appear as:

JS

<iframe style={{ width: 1920 }} />

2. Scale the Iframe Up or Down

Our fixed-width <iframe> needs to be scaled up or down, depending on the available space on the page.

E.g. if the <iframe> has a fixed width of 1920px but we only have 960px available, we need to scale it by 0.5.

JS

<iframe style={{ width: 1920, transform: 'scale(0.5)' }} />

3. Apply the Scale Dynamically

By measuring the width of the iframe's container, we can calculate a scaleFactor that tells us by how much we need to scale the iframe up or down in order to fill the available horizontal space.

JS

const breakpoint = 1920
const scaleFactor = container.clientWidth / breakpoint
const style = {
width: breakpoint,
transform: `scale(${scaleFactor})`,
transformOrigin: 'top left',
}
return (
<div ref={containerRef}>
<iframe ref={iframeRef} style={style} />
</div>
)

4. Adjust the Iframe's Height

When you scale down an element using CSS, the entire element becomes smaller.

So if we want the <iframe> to fill the height of its parent, we need to adjust the height after scaling it down.

JS

// ...
const style = {
width: breakpoint,
height: container.clientHeight / scaleFactor,
transform: `scale(${scaleFactor})`,
transformOrigin: 'top left',
}
// ...

And that's the basics of a simple iframe-based responsive website tester!

Source Code and Working Example

Check out the entire working example on CodeSandbox.

It includes proper state management and uses a ResizeObserver to correctly respond to changes in the viewport's size.