Don’t Use ‘display: none’ to Hide iFrames in Safari

Zach C
Zach C
Nov 5, 2017 · 2 min read
Image for post
Image for post
@crystalahuff on unsplash

It’s common to use iFrames to serve up content and track users on websites. Quite often you don’t need or want the iFrame to be visible.

While working on a browser extension for Chrome, Firefox, Edge, and Safari I used display: none to hide an iFrame. When the user clicked a button, the property changed from display: none to display: block. Easy right?

This obvious solution works great in Chrome, Firefox, and Edge. But in Safari, the div would never appear when display was set back to block.

It turns out that Safari won’t add iFrames with a display: none property to the DOM on the initial page load. This means that if you ever decide to reveal your element later, it won’t be available on the DOM. Yikes!

The Problem with visibility: hidden

You might think we could use visibility: hidden and visibility: visible to solve this. But if you set a parent container to visibility: hidden, its children will also be set to hidden. When you toggle visibility back to visible, the children will still be invisible.

You’ll have to set each child back to visible. Clunky and annoying.

You could also set the children to visibility: inherit, which will allow the parent container to set the child’s visibility. This is better, but still requires you to specify visibility on each child element.

Use Opacity

My preferred solution is to use opacity. Here’s why.

On the initial page load, your iFrame can be invisible to the user, but Safari will still add it to the DOM. Awesome!

But it gets better still. By definition, child elements inherit their parent’s opacity. It doesn’t make sense that a container would be transparent if everything it contained was opaque.

So toggling our parent from opacity: 0 to opacity: 1 will make all child elements visible and invisible as needed. But we don’t have to fuss with visibility: inherit.

The opacity approach gets us there and Safari still adds it to the DOM on initial load.

Happy hacking!

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store