Card; responsive Iframes

Responsive Iframes

Iframes that fit like a tailored suit

Iframes are fantastic, no doubt about it—they’re windows to other worlds. But sometimes, they feel like a stiff, ill-fitting suit, no matter how much you adjust or tweak them.

That’s where CSS steps in, like a skilled tailor. With the right techniques, it ensures your iframe adapts seamlessly to any screen size, as if custom-made. A few clever tricks, and your iframe will stretch and shrink gracefully, always maintaining its perfect form. Whether on a massive desktop or a tiny mobile screen, your window to other worlds stays stylish and refined.

Iframes responsive

Token: styling Iframes

A Window

That Adapts

To make an iframe responsive, you can place it inside a container with a fixed aspect ratio.

In this example, the iframe-container ensures the iframe maintains a 16:9 aspect ratio, typical for videos. The ratio is set using padding-bottom (56.25% corresponds to 16:9). The iframe is then resized to fill the entire width of the container, regardless of screen size.
Don’t worry too much about the position property yet— you’ll get to know it well when you meet the Weirdos!

HTML
<div class="iframe-container">
    <iframe src="https://www.example.com" frameborder="0" allowfullscreen>
    </iframe>
</div>
CSS
.iframe-container {
    position: relative;
    width: 100%;
    padding-bottom: 56.25%;
    /* For a 16:9 aspect ratio */
    height: 0;
    overflow: hidden;
}

.iframe-container iframe {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}
HTML
<!-- Youtube without CSS -->
<iframe width="560" height="315" src="https://www.youtube-nocookie.com/embed/o1JIK5W3DRU?si=gLp-so-mNBvlGgYs" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>

<!-- Youtube with CSS -->
<div class="iframe-container">
    <iframe frameborder="0" allowfullscreen src="https://www.youtube-nocookie.com/embed/WhWc3b3KhnY?si=WjzAbnmVkseYr38-" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div>
CSS
.iframe-container {
    position: relative;
    width: 90%;
    padding-bottom: 56.25%;
    /* For a 16:9 aspect ratio */
    height: 0;
    overflow: hidden;
}

.iframe-container iframe {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}
Scroll to Top