美文网首页
iframe 自适应宽高

iframe 自适应宽高

作者: 想溜了的蜗牛 | 来源:发表于2021-05-07 21:52 被阅读0次

尽管 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.

相关文章

  • iframe宽高自适应

    Title window.onload = function...

  • iframe 自适应宽高

    尽管 iframe 不好控制,但在前端中还是有一些场景它确实算好用。比如一个系统需要引入第三方的页面,此时只需要页...

  • 实现iframe内容页拖拽代替滚动条滚动

    需求:用iframe标签链接一个网页,iframe设置固定宽高,隐藏滚动条,当内容页宽高大于iframe宽高,拖动...

  • image 居中且图片不变形

    保持高宽比率 图片居中不变形,网上有不少方法,但多少有点问题。在上一篇 iframe 自适应宽高[https://...

  • iOS Masonry布局(二) - UILabel

    UILabel自适应宽高 UILabel使用Masonry布局时如果不添加宽高约束,视图会根据内容自适应宽高。 示...

  • Iframe高度自适应

    1. 同域iframe高度自适应 2. 跨域iframe高度自适应

  • 图片自适应

    1.平均分为3份,图片宽 根据 屏幕宽 自适应,图片宽高 根据 图片宽 的大小自适应,始终不会扭曲 图片...

  • 使用UILabel显示富文本的时候图片宽高自适应方法

    在使用UILabel显示富文本的时候(包含图片),有图片的情况下图片宽高不能自适应,图片宽高自适应方法如下: de...

  • 高度塌陷

    1、自适应宽高 (1)块级元素宽度设置为100%,或者不设置,默认为父元素的宽 (2)高度自适应:不设置父元素的高...

  • HTML经常用到的标签详解

    iframe标签 嵌套其他页面默认的宽高是50px,100px可以自定宽高 a标签 QQ 在空页面...

网友评论

      本文标题:iframe 自适应宽高

      本文链接:https://www.haomeiwen.com/subject/aogedltx.html