Maintaining Aspect Ratio while Filling Screen Width and Height in CSS
Problem:
Creating a div element with a fixed aspect ratio that fills the entire screen width and height without exceeding its boundaries.
Solution:
Utilize the CSS viewport units vw and vh to set the dimensions of the div.
CSS Implementation:
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 */ }
Explanation:
Result:
The div element expands to fill the available screen space without breaking its aspect ratio, regardless of the device's orientation or screen size.
The above is the detailed content of How to Maintain Aspect Ratio While Filling the Entire Screen with CSS?. For more information, please follow other related articles on the PHP Chinese website!