Home >Web Front-end >CSS Tutorial >How to Maintain a 16:9 Aspect Ratio for a Div Filling the Entire Screen?
When designing a website with a specific aspect ratio, such as 16:9 for a video-like display, it becomes necessary to maintain this ratio while filling the available screen space. This task presents challenges in ensuring that the content is centered and never exceeds the maximum dimensions on either side.
Applying the CSS Viewport Units
A practical CSS solution involves using the viewport units, vw (viewport width) and vh (viewport height). These units allow the element to adjust its dimensions relative to the viewport's size. By setting the div's width to 100vw, it expands to fill the entire screen width. To maintain the 16:9 aspect ratio, the height is set to 56.25vw (calculated as 9/16 * 100vw).
Constraining the Maximum Dimensions
To prevent the element from overflowing, maximum height and width constraints are applied using max-height: 100vh and max-width: 177.78vh (calculated as 16/9 * 100vh).
Positioning and Centering
The div is positioned and centered both vertically and horizontally using absolute positioning and setting top, bottom, left, and right to 0. This ensures that the div stays centered within the screen's available space.
By combining these CSS properties, you can create a div that maintains its aspect ratio of 16:9 while filling the entire screen width and height. This solution is responsive and works consistently across major browsers without the need for JavaScript.
The above is the detailed content of How to Maintain a 16:9 Aspect Ratio for a Div Filling the Entire Screen?. For more information, please follow other related articles on the PHP Chinese website!