In this post, I will show you how to build a simple responsive website tester using the "scaling iframe" technique.
If you use an <iframe>
with width: 100%;
, the content of the iframe behaves responsively and is dependent on the available space:
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:
This is what we'll use for our responsive website tester.
This "scaling iframe" requires a bit of JavaScript. The general strategy is simple:
The <iframe>
element will have a fixed width, the same as the breakpoint we want the website to appear as:
<iframe style={{ width: 1920 }} />
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)' }} />
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 = 1920const scaleFactor = container.clientWidth / breakpointconst style = {width: breakpoint,transform: `scale(${scaleFactor})`,transformOrigin: 'top left'}return (<div ref={containerRef}><iframe ref={iframeRef} style={style} /></div>)
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!
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.
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.