# CSS Aspect Ratio

I fought a lot to find a solid way to maintain aspect ratio of an inner HTML element, so I want to preserve it here for future reference.

The square element will always remain a square that fills as much available space as possible. It can have horizontal or vertical bars of space on the sides.

/* Full-screen top-level frame. */
html,
body {
  width: 100%;
  height: 100%;
  margin: 0px;
  overflow: hidden;
  touch-action: none;
}

/* The main is the topmost box that's always full height. */
.main,
.square {
  display: flex;
  align-items: center;
  justify-content: center;
}

.main {
  min-height: 100vh;
}

/* Square is the inner element that always remains a square. Fill this with stuff. */
.square {
  width: 100vmin;
  height: 100vmin;
}
<html>
  <head>
    <meta charset="utf-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, maximum-scale=1,user-scalable=no"
    />
    <link rel="stylesheet" href="styles.css" />
  </head>
  <body>
    <div class="main">
      <div class="square"></div>
    </div>
  </body>
</html>