Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS aspect ratio with maximum height

I have a section that i want to scale using aspect ratio, but also keep it at a maximum and minimum height. Somehow the max-height property doesn't apply to this, meanwhile the min-width works just fine.

div {
  background: green;
  border-bottom: 2px solid red;
  padding-top: 60%;
  max-height: 100vh;
  min-height: 450px;
  box-sizing: border-box;
 }
<div></div>

What i'm trying to achieve is to display content that has a fixed aspect ratio, it scales down until reaches a minimum height, but also won't exceed the viewport height when displayed in a wider browser. See attached image for explanation:

enter image description here

Any ideas?

like image 567
passatgt Avatar asked Jun 03 '26 20:06

passatgt


1 Answers

Ok, if I understand correctly, you'd need to do have the height of the box linked to the width at a percentage (which I'd do by setting the height to viewport width units rather than viewport height - in my example I've set it to 75%). That way the box stays in pro when it's not being constrained by max-height or min-height.

html, 
body {
    width: 100%;
    height: 100%;
    padding: 0px;
    margin: 0px;
    background-color: #00ff00;
}

.box {
    width: 100%;
    height: 75vw;
    max-height: 100vh;
    min-height: 400px;
    background-color: #ff0000;
}

like image 95
Darren Crabb Avatar answered Jun 06 '26 07:06

Darren Crabb