Home >Web Front-end >CSS Tutorial >How to Maintain a Div's Aspect Ratio While Filling the Entire Screen in CSS?

How to Maintain a Div's Aspect Ratio While Filling the Entire Screen in CSS?

Linda Hamilton
Linda HamiltonOriginal
2024-12-18 18:50:15726browse

How to Maintain a Div's Aspect Ratio While Filling the Entire Screen in CSS?

Maintain Aspect Ratio of Div While Filling Screen Width and Height in CSS

To maintain the aspect ratio of a div while filling the screen's width and height, we can utilize the CSS viewport units vw (viewport width) and vh (viewport height). This approach ensures that the element will always fill the maximum viewport size without breaking the ratio or creating scrollbars.

FIDDLE

Pure CSS

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 */
}

This CSS ensures that the div:

  • Expands to encompass the full width and height of the screen (vw and vh units).
  • Maintains an aspect ratio of 16:9 (height:width ratio of 56.25vw:100vw).
  • Prevents overflow by setting maximum height and width constraints.
  • Centers the div vertically and horizontally within the available viewport space.

The above is the detailed content of How to Maintain a Div's Aspect Ratio While Filling the Entire Screen in 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