步骤1:设置包含iframe的父元素
 
首先,确保iframe的父容器具有一个适当的宽高比。通过为父容器设置一个相对定位和一定的宽度和高度,你可以控制它的尺寸。
<div class="video-container"><iframe src="https://www.example.com" frameborder="0" allowfullscreen></iframe>
</div>
步骤2:应用CSS样式
接下来,使用CSS来确保iframe在父容器中保持宽高比并响应不同的屏幕尺寸。
.video-container {position: relative;width: 100%;padding-bottom: 56.25%; /* 16:9 aspect ratio (height/width = 9/16 = 0.5625) */height: 0;overflow: hidden;
}.video-container iframe {position: absolute;top: 0;left: 0;width: 100%;height: 100%;border: 0;
}
解释:
- .video-container:- position: relative;使得内部元素(即- iframe)可以根据父容器定位。
- padding-bottom: 56.25%;这是16:9视频比例的常用宽高比(可以根据实际视频比例调整,例如4:3为- 75%)。
- height: 0;与- padding-bottom配合使用,通过比例控制高度。
 
- .video-container iframe:- position: absolute;确保- iframe相对于父容器的顶角定位。
- width: 100%;和- height: 100%;确保- iframe填充整个父容器,从而适应不同的屏幕大小。
 
这样,无论是桌面端、平板还是手机,iframe里的视频都会根据容器的宽度自适应高度,保持比例不变。