Home > Mobile >  How to make a div have 100vh while maintaining the aspect ratio?
How to make a div have 100vh while maintaining the aspect ratio?

Time:12-09

I'm trying to make a circle with a 1:1 aspect ratio to have width: 100vh; height: 100vh; properties so the circle should grow the maximum possible but not lose its aspect ratio or overflow the viewport. It works for the width, but I couldn't figure out any property that would force the circle's height to remain 100vh;.

I tried to set the HTML tag to height: 100% as well as the body tag. I tried position: absolute on the body and set the top, right, bottom, and left properties. Nothing seems to work.

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
html {
  width: 100%;
  height: 100%;
}
body {
  width: 100%;
  height: 100%;
}
.circle {
  padding-top: 100%; /* sets a 1:1 aspect ratio */
  border-radius: 100%;
  border: 1px solid red;
  width: 100%;
  max-height: 100vh !important;
  overflow: hidden;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <main ></main>
</body>
</html>

CodePudding user response:

100vmin and aspect-ratio can do the job

.circle {
  border-radius: 100%;
  border: 1px solid red;
  width: 100vmin;
  aspect-ratio: 1/1;
  box-sizing: border-box;
}

body {
  display:grid;
  place-content:center;
  min-height:100vh;
  margin: 0;
}
<main ></main>

  • Related