Home >Web Front-end >CSS Tutorial >How to Maintain Aspect Ratio While Filling the Entire Screen with CSS?

How to Maintain Aspect Ratio While Filling the Entire Screen with CSS?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-24 01:07:14927browse

How to Maintain Aspect Ratio While Filling the Entire Screen with CSS?

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:

  • Viewport Units: vw and vh measure units relative to the viewport width and height, respectively.
  • Aspect Ratio: The height is set to 56.25% of the width, maintaining a constant 9:16 aspect ratio.
  • Max Dimensions: The element is constrained within the viewport dimensions using max-height and max-width.
  • Centering: The position property centers the element both vertically and horizontally on the screen using top:0; bottom:0; and left:0; right:0;.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn