1

So this has been driving me crazy and I am wondering if there is a way to do this with pure CSS. What I am trying to do is have a parent div (purple) with a fixed height. Inside that purple div I want the orange div to maintain aspect ratio and scale up to the height of the parent div. If I change the size of the parent div the orange div should scale accordingly with its aspect ratio.

Note: Trying to do this without an image or percentage parent heights.

See Example: enter image description here

tkruse
  • 10,222
  • 7
  • 53
  • 80
Andrew Dotson
  • 311
  • 2
  • 6
  • Possible duplicate of [Maintain div aspect ratio according to height](http://stackoverflow.com/questions/26438388/maintain-div-aspect-ratio-according-to-height) – Jon Uleis Dec 16 '16 at 18:51
  • No I am trying to do this without an image and fixed px height for the parent. – Andrew Dotson Dec 16 '16 at 18:55
  • The image is part of the trick - you can make it a transparent (invisible) 1x1 PNG and still accomplish the task. That method allows the parent to be any height, not a fixed px amount. – Jon Uleis Dec 16 '16 at 18:57
  • I am looking for a solution that does not involve using an image at all (for semantic purposes). Hoping there is another trick or way to do this. – Andrew Dotson Dec 16 '16 at 19:19

2 Answers2

1

A solution using aspect-ratio, resize the parent on the bottom right:

#parent {
  /* fluff */
  background-color: #d121ae;
  resize: both;
  height: 100px;
  overflow: auto;
}

#child {
  /* the useful bits */
  aspect-ratio: 1;
  max-height: 100%;
  
  /* fluff */
  background-color: #ffce1c;
}
<div id="parent">
  <div id="child"></div>
</div>
mrossman
  • 561
  • 4
  • 12
0

You can do it with some simple JS. Just get the height of the child (or parent) and set the width. You can use calculations as necessary to get the ratio you want.

var width = document.getElementById('child').offsetHeight;
document.getElementById('child').style.width = width + 'px';
#parent{
  width: 100%;
  height: 100px;
  background-color: purple;
}
#child{
  height: 100%;
  background-color: yellow;
}
<div id="parent">
  <div id="child"></div>
</div>
mhatch
  • 4,441
  • 6
  • 36
  • 62
  • Thanks for sending this. Do you think JS is the only way? I am trying to solve it with pure css. Playing around with flex box and a few other margin hacks to see if I can get it working. – Andrew Dotson Dec 16 '16 at 19:43
  • There is a `calc` function in css which can allow you to do some things, but what you really need is a css variable... and that is not cross-browser supported. – mhatch Dec 16 '16 at 19:47
  • I ended up just using sass – Andrew Dotson Dec 16 '16 at 20:49