html - CSS vw and vh but relative to the parent instead of viewport -


i'm trying create fixed aspect ratio box resizes not overflow parent.

the classic padding-bottom trick able define height in terms of parent width, , testable here allows element grow taller parent width increases. not good.

using vh , vw however, can accomplish want restriction parent dimensions of viewport. testable here.

<style>   div {     max-width: 90vw;     max-height: 90vh;     height: 50.625vw; /* height defined in terms of parent width (90*9/16) */     width: 160vh; /* width defined in terms of parent height, missing padding-bottom trick (90*16/9) */     background: linear-gradient(to right, gray, black, gray);   } </style>  <div></div> 

is there way have vh , vw equivalent references parent instead of viewport? or there complimentary trick padding-bottom trick fixes problems? css ratio property?

also, images have sort of intrinsic ratio, i'm unsure how take advantage of this.

you can use similar did in maintain aspect ratio fixed height, takes advantage intrinsic aspect ratio of <canvas> elements.

but here need nested containers 2 canvas.

#resize {    resize: both;    overflow: auto;    width: 100px;    height: 140px;    padding: 20px;    border: 1px solid black;  }  .ratio {    position: relative;    display: inline-block;    vertical-align: middle;  }  .ratio.vertical, .ratio.vertical > canvas {    height: 100%;    max-width: 100%;  }  .ratio.horizontal, .ratio.horizontal > canvas {    width: 100%;    max-height: 100%;  }  .ratio > div {    position: absolute;    top: 0;    right: 0;    bottom: 0;    left: 0;  }  #contents {    background: linear-gradient(to right, gray, black, gray);  }
<div id="resize">    <div class="ratio vertical">      <canvas width="16" height="9"></canvas>      <div>        <div class="ratio horizontal">          <canvas width="16" height="9"></canvas>          <div id="contents">            hello          </div>        </div>      </div>    </div>  </div>


Comments

Popular posts from this blog

amazon web services - S3 Pre-signed POST validate file type? -

c# - Check Keyboard Input Winforms -