Explain Codes LogoExplain Codes Logo

How to get an IFrame to be responsive in iOS Safari?

html
responsive-design
css
javascript
Anton ShumikhinbyAnton Shumikhin·Sep 7, 2024
TLDR

To make an IFrame responsive in iOS Safari, use width: 100%; and encapsulate within a wrapper div that manages the aspect ratio. Set the height relative to width using padding-top56.25% suits a 16:9 ratio.

Here's the basic structure:

<div style="position: relative; width: 100%; padding-top: 56.25%;"> <iframe src="your-source.html" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;"></iframe> </div>

This piece of code makes the IFrame adaptable while keeping the aspect ratio intact.

Fine-tuning scrolling, avoiding overflow

Taming the scrolling behavior in IFrames involves overflow: auto; along with -webkit-overflow-scrolling: touch; for smoother scrolling in iOS. Wrapping the IFrame in a Div with these styles helps control overflow:

<!-- Make sure your fluid stays in your lava lamp. --> <div style="overflow: scroll; -webkit-overflow-scrolling: touch;"> <iframe src="your-content.html" scrolling="no"></iframe> </div>

To avoid the beast that is auto-expansion, use the viewport width unit vw for your IFrame's width:

<!-- Now the lamp is on a diet, never getting chubby. --> <iframe src="your-content.html" style="width: 100vw; max-width: 100%;" scrolling="no"></iframe>

Get the perfect fit with customization

For peculiar situations like double scrollbar issues on desktop, browser detection is your superhero. When on an iOS device, feel free to hide the outer scrollbar.

// Call on good old Sherlock Holmes to detect iOS. const userAgent = navigator.userAgent || navigator.vendor || window.opera; if (/iPad|iPhone|iPod/.test(userAgent) && !window.MSStream) { // Adjusts settings specifically for iOS interface. Elementary, my dear Watson. }

Sometimes, position: fixed; is mandatory for IFrames within dynamic containers:

#wrap { // By doing this, we put a leash on our container. Sit, boy! position: fixed; overflow-y: scroll; }

Correctly setting the height property of an IFrame for a fixed position prevents iOS Safari from taking the liberty to resize it. Use JavaScript to calculate and set the height.

The devil is in the detail: edge cases

Apple's no-scroll default influences IFrames. We trick it by directly adjusting the IFrame content width, resulting in better responsiveness.

JavaScript-oriented adaptations are invaluable. Use it to specify IFrame attributes responsibly:

// For those into weight-lifting, resize is your favorite exercise routine. window.addEventListener('resize', function(){ let iframe = document.getElementById('responsive-iframe'); // "Do you even lift, bro?" iframe.style.height = window.innerHeight + 'px'; iframe.style.width = window.innerWidth + 'px'; });

Lastly, ensure cross-browser compatibility is on your checklist. Utilize caniuse.com for evaluating viewport units support and CSS property adherence.