How does this responsive-iframe-container snippet work?

前端 未结 1 1507
灰色年华
灰色年华 2021-02-10 05:26

I don\'t recall how I\'ve found this code and applied it with no issues at all:

/* Responsive iFrame */

.responsive-iframe-container {
    posi         


        
1条回答
  •  暖寄归人
    2021-02-10 05:50

    Well, for whatever reason (often I find answers while asking questions, and delete the question), I just decided to google for responsive iframe and found this as the second result, which is probably where the code came from. It explains everything in detail and, basically, it is actually all together that makes it work and vresponsive has nothing to do with it.

    Quoting from its summary:

    Embedded content has a habit of breaking responsive layouts, because it’s contained in an iframe with a fixed width. In this article, we’ve seen how to add a single containing wrapper, and some CSS, to ensure that all embedded content contained in an iframe resizes with the browser’s window.

    And from the part it explains a bit about each detail there:

    .video-container {
        position: relative;
        padding-bottom: 56.25%;
        padding-top: 30px;
        height: 0;
        overflow: hidden;
    }
    

    This does a few things:

    • Setting the position to relative lets us use absolute positioning for the iframe itself, which we’ll get to shortly.
    • The padding-bottom value is calculated out of the aspect ratio of the video. In this case, the aspect ratio is 16:9, which means that the height will be 56.25% of the width. For a video with a 4:3 aspect ratio, we set padding-bottom to 75%.
    • The padding-top value is set to 30 pixels to allow space for the chrome — this is specific to YouTube videos.
    • The height is set to 0 because padding-bottom gives the element the height it needs. We do not set the width because it will automatically resize with the responsive element that contains this div.
    • Setting overflow to hidden ensures that any content protruding outside of this element will be hidden from view.

    We also need to style the iframe itself. Add the following to your style sheet:

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

    This targets iframes inside containers with the .video-container class. Let’s work through the code:

    • Absolute positioning is used because the containing element has a height of 0. If the iframe were positioned normally, we would have given it a height of 0 as well.
    • The top and left properties position the iframe correctly in the containing element.
    • The width and height properties ensure that the video takes up 100% of the space used by the containing element (which is actually set with padding).

    Having done this, the video will now resize with the screen’s width.

    0 讨论(0)
提交回复
热议问题