Responsive iframe with max width and height

I have a fixed height container containing both images and iframes. To make the images responsive and preventing both vertical and horizontal overflow I can just set the following CSS:

img {
    max-width: 100%;
    max-height: 100%;
}

This ensures that a portrait image would not overflow vertically and a landscape image would not overflow horizontally.

For iframes, I’m using the “padding-ratio” technique, setting the padding of the wrapper element to the aspect ratio of the iframe (e.g. 56.25% for a 16:9 video):

.iframe-wrapper {
    position: relative;
    height: 0;
    padding-top: 56.25%;
    overflow: hidden;
}

.iframe-wrapper iframe {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

While this means that the iframe scales with the width of the viewport it does not work the same if I change the height of the viewport. Essentially I’d like the iframe to mimic how the images work.

Leave a Comment