Max SchmittMS
28th February 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:

<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.

<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.

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.

// ...
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.

Image of my head

About the author

Hi, I’m Max! I'm a fullstack JavaScript developer living in Berlin.

When I’m not working on one of my personal projects, writing blog posts or making YouTube videos, I help my clients bring their ideas to life as a freelance web developer.

If you need help on a project, please reach out and let's work together.

To stay updated with new blog posts, follow me on Twitter or subscribe to my RSS feed.