iframe video calls adaptive page size using css control (also suitable for other elements)

In order to make the video in the iframe adaptive to the page size, you can use CSS to control its width and height. It is convenient for adaptive display size on computers and mobile phones. It is quite common in actual projects. Using CSS does not require writing JS to control it. This is quite good.

First, in the HTML file, embed the iframe into a wrapping element (e.g.

) and assign the wrapper element a class name (e.g. video-box):

<!DOCTYPE html>
<html lang="cn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>我是视频标题</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="video-box">
        <iframe src="您的视频外链地址" frameborder="0" allowfullscreen></iframe>
    </div>
</body>
</html>

In a CSS file (e.g. styles.css), use the following CSS styles to control the size of the box-container and iframe:

/* 设置iframe的宽度和高度为100%,以适应包装元素的大小 */
iframe {
    
    
    width: 100%;
    height: 100%;
}
 
/* 设置包装元素的宽度和高度,并设置宽度为100%以适应父元素的宽度 */
.video-box {
    
    
    position: relative;
    width: 100%;
    height: 0;
    padding-bottom: 56.25%; /* 设置宽高比为16:9,可根据需要更改 */
    overflow: hidden;
}
 
/* 使iframe相对于包装元素定位,以保持宽高比 */
.video-box iframe {
    
    
    position: absolute;
    top: 0;
    left: 0;
}

This example uses a 16:9 aspect ratio, you can change the value of padding-bottom to set a different aspect ratio if needed. Using this method, the video in the iframe will automatically adjust to the page size and always maintain the correct aspect ratio.

Guess you like

Origin blog.csdn.net/likeni1314/article/details/129896147