Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertically center responsive iframe

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%;
}

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

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.

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/

like image 547
Ben Foster Avatar asked Feb 08 '14 11:02

Ben Foster


1 Answers

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

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;
}

Fiddle has been updated.

like image 180
Ben Foster Avatar answered Oct 22 '22 00:10

Ben Foster