尽管 iframe 不好控制,但在前端中还是有一些场景它确实算好用。
比如一个系统需要引入第三方的页面,此时只需要页面能做好自适应就可以了。打通登录信息的情况这时太不讲。
iframe 自适应相应的文章可以参考这Responsive Iframes with One Great CSS Trick。 下文仅将重要代码摘录,想了解更多的看原文。
HTML:
<div class="resp-container">
<iframe class="resp-iframe" src="https://www.youtube.com/embed/dQw4w9WgXcQ" gesture="media" allow="encrypted-media" allowfullscreen></iframe>
</div>
CSS
.resp-container {
position: relative;
overflow: hidden;
padding-top: 56.25%;
}
- position: relative The position of both the wrapper and the iframe is very important here. We are setting it to a position: relative so that we can later position our iframe in relation to the wrapping element. This is because in CSS, position: absolute positions the element based on the closest non static parent element.
- overflow: hidden is there to hide any elements that might be placed outside of the container.
- padding-top: 56.25% This is where the magic is. In CSS, the padding-top property can receive a percentage, this is what keeps our iframe to the right ratio. By using percentage, it will calculate the padding to use based on the width of the element. In our example, we want to keep the ratio of 56.26% (height 9 ÷ width 16) because this is the default ratio for YouTube videos. However, other ratios can be used as well. (这里 56.26% 的算法是用的 高/宽, 也可以是其它比例的值)
.resp-iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
border: 0;
}
- position: absolute; This will give the iframe a position relative to the wrapper and let it be positioned over the padding of the wrapper.
- top: 0 and left: 0 are used to position the iframe at the center of the container.
- width: 100% and height: 100% make the iframe take all of the wrapper’s space.
网友评论