I have a site to put together that has a fixed aspect ratio of approximately 16:9
landscape, like a video.
I want to have it centred and expand to fill the available width, and the available height, but never to grow larger on either side.
For example:
There are two methods I've been looking at:
div
, but I couldn't get it to behave the same way across major browsers. I know you could do this with JS quite easily, but I'd like a pure CSS solution.
Any ideas?
Use the new CSS viewport units vw
and vh
(viewport width / viewport height)
Resize vertically and horizontally and you'll see that the element will always fill the maximum viewport size without breaking the ratio and without scrollbars!
div
{
width: 100vw;
height: 56.25vw; /* height:width ratio = 9/16 = .5625 */
background: pink;
max-height: 100vh;
max-width: 177.78vh; /* 16/9 = 1.778 */
margin: auto;
position: absolute;
top:0;bottom:0; /* vertical center */
left:0;right:0; /* horizontal center */
}
* {
margin: 0;
padding: 0;
}
div {
width: 100vw;
height: 56.25vw;
/* 100/56.25 = 1.778 */
background: pink;
max-height: 100vh;
max-width: 177.78vh;
/* 16/9 = 1.778 */
margin: auto;
position: absolute;
top: 0;
bottom: 0;
/* vertical center */
left: 0;
right: 0;
/* horizontal center */
}
<div></div>
If you want to use a maximum of say 90% width and height of the viewport: FIDDLE
* {
margin: 0;
padding: 0;
}
div {
width: 90vw;
/* 90% of viewport vidth */
height: 50.625vw;
/* ratio = 9/16 * 90 = 50.625 */
background: pink;
max-height: 90vh;
max-width: 160vh;
/* 16/9 * 90 = 160 */
margin: auto;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
<div></div>
Also, browser support is pretty good too: IE9+, FF, Chrome, Safari- caniuse