垂直居中响应 iframe [英] Vertically center responsive iframe

查看:28
本文介绍了垂直居中响应 iframe的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此处描述的技术来制作 iframe(视频)响应式.本质上,iframe 绝对位于具有 100% 宽度的包装元素内.包装元素根据视频的纵横比设置了填充:

I'm using the technique described here to make an iframe (video) responsive. Essentially the iframe is absolutely positioned within a wrapper element with a 100% width. The wrapper element has it's padding set based on the aspect ratio of the video:

.embed-responsive {
    position: relative;
    /* video height / video width */
    padding-bottom: 56.2%;
    height: 0;
    overflow: hidden;
}
.embed-responsive iframe {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

我需要能够将 iframe 在父容器(高度为 100%)中垂直居中.

I need to be able to center the iframe vertically in the parent container (which has a 100% height).

我在使用这种技术之前已经实现了这一点,但它只有效在 inline-block 元素上.如果我将 .embed-responsive 更改为 inline-block 它会中断.

I've achieved this before using this technique but it only works on inline-block elements. If I change .embed-responsive to inline-block it breaks.

那么有没有替代的技术(最好只有 CSS)可以用来垂直居中 iframe,同时仍然具有响应性?这必须在调整浏览器大小时起作用.

So is there an alternative (preferably CSS only) technique I can use to vertically center the iframe, whilst still being responsive? This must work as the browser is resized.

http://jsfiddle.net/benfosterdev/xfA3L/

推荐答案

所以我在发布 2 分钟后就想通了:)

So I figured this out after 2 minutes of posting :)

使 .embed-resposive 绝对定位,top:50% 和 margin top 设置为高度比例的一半 (video height/video width)/2 我可以垂直居中:

Making .embed-resposive absolutely positioned with top:50% and margin top set to half the height ratio (video height / video width) / 2 I can center it vertically:

.embed-responsive {
    position: absolute;
    left: 0; right: 0;
    top: 50%;
    /* video height / video width */
    padding-bottom: 56.2%;
    /* the above value * 0.5 */
    margin-top: -28.1%;
    height: 0;
    overflow: hidden;
}

小提琴已更新.

这篇关于垂直居中响应 iframe的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆