To maintain the aspect ratio of a div according to width and height in the viewport, you can use one HTML tag with:
- vmin units for the sizing :
vmin 1/100th of the minimum value between the height and the width of the viewport.
(source : MDN)
position: absolute
and margin: auto;
for the centering
DEMO (resize both window height and width to see it in action)
Features :
- keeps it's aspect ratio according to width and height
- stays centered in viewport horizontaly and verticaly
- never overflows the viewport
Browser support :
vmin
units are supported by IE10+ (canIuse) for IE9 support, you need to use a fallback with vm
units instead of vmin
like this :
width: 100vm; /* <-- for IE9 */
height: 100vm; /* <-- for IE9 */
width: 100vmin;
height: 100vmin;
Full code:
body {
margin:0; /* To prevent scrollbars */
}
div{
/* Aspect ratio */
height:100vm; width:100vm; /* IE9 fallback */
width: 100vmin;
height: 100vmin;
/*Centering */
position: absolute;
top:0;bottom:0;
left:0;right:0;
margin: auto;
/* styling */
background: gold;
}
<div>whatever content you wish</div>