Use a CSS media query @media
together with the CSS viewport units vw
and vh
to adapt to the aspect ratio of the viewport. This has the benefit of updating other properties, like font-size
, too.
This fiddle demonstrates the fixed aspect ratio for the div, and the text matching its scale exactly.
Initial size is based on full width:
div {
width: 100vw;
height: calc(100vw * 9 / 16);
font-size: 10vw;
/* align center */
margin: auto;
position: absolute;
top: 0px; right: 0px; bottom: 0px; left: 0px;
/* visual indicators */
background:
url(data:image/gif;base64,R0lGODlhAgAUAIABAB1ziv///yH5BAEAAAEALAAAAAACABQAAAIHhI+pa+EPCwA7) repeat-y center top,
url(data:image/gif;base64,R0lGODlhFAACAIABAIodZP///yH5BAEAAAEALAAAAAAUAAIAAAIIhI8Zu+nIVgEAOw==) repeat-x left center,
silver;
}
Then, when the viewport is wider than the desired aspect ratio, switch to height as base measure:
/* 100 * 16/9 = 177.778 */
@media (min-width: 177.778vh) {
div {
height: 100vh;
width: calc(100vh * 16 / 9);
font-size: calc(10vh * 16 / 9);
}
}
This is very similar in vein to the max-width
and max-height
approach by @Danield, just more flexible.