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:
- A tall and thin page would have the content stretching the full width while maintaining a proportional height.
- A short wide page would have the content stretching the full height, with a proportional width.
There are two methods I've been looking at:
- Use an image with the right aspect ratio to expand a container
div
, but I couldn't get it to behave the same way across major browsers. - Setting a proportional bottom padding, but that only works relatively to the width and ignores the height. It just keeps getting bigger with the width and displays vertical scroll bars.
I know you could do this with JS quite easily, but I'd like a pure CSS solution.
Any ideas?
Best Answer
Use the new CSS viewport units
vw
andvh
(viewport width / viewport height)FIDDLE
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!
(PURE) CSS
If you want to use a maximum of say 90% width and height of the viewport: FIDDLE
Also, browser support is pretty good too: IE9+, FF, Chrome, Safari- caniuse