Alex F Alex F - 4 months ago 22
CSS Question

Keep the aspect ratio of a div with CSS

Is there any chance to maintain aspect ratio of DIV with max-height option?

There is a solution to keep aspect ratio:

div.stretchy-wrapper {
position: relative;
width: 100%;
padding-bottom: 75%;
background:gold; /** <-- For the demo **/
}

div.stretchy-wrapper > div {
position: absolute;
top: 0; bottom: 0; left: 0; right: 0;
}


It works perfect but what if want to keep DIV re-sizable but up to certain height? Let's say I want DIV stop re-sizing once it's height reaches 200px. Any ideas? Thank you in avance.

Answer

Try:

div.stretchy-wrapper {
  position: relative;
  max-width: 400px; /* or your max-width */
  max-height: 300px; /* or your max-height */
}
div.stretchy-wrapper > div {
  z-index: 1;
  position: absolute;
}
div.stretchy-wrapper > div:last-child {
  z-index: 0;
  position: relative;
  padding-bottom: 75%;
  background: gold; /** <-- For the demo **/
}

<div class="stretchy-wrapper"><div>Content...</div><div></div></div>

Comments