Skip to content

Instantly share code, notes, and snippets.

@mutongwu
Created March 18, 2020 02:16
Show Gist options
  • Save mutongwu/897b059d8b090ea379b537a25b8c3fe2 to your computer and use it in GitHub Desktop.
Save mutongwu/897b059d8b090ea379b537a25b8c3fe2 to your computer and use it in GitHub Desktop.

Revisions

  1. mutongwu created this gist Mar 18, 2020.
    60 changes: 60 additions & 0 deletions .html
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,60 @@
    //https://codepen.io/aghassemi/pen/RpdaKM
    <div style="height:320px">

    <div class="parent">
    <div class="wrapper">
    <!-- To change aspect ratio, change SVG's width/height -->
    <img class="resizer" src='data:image/svg+xml;utf8,<svg height="2px" width="1px" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1"></svg>'></img>
    <div class="child">Child maintains aspect ratio as parent's height changes</div>
    </div>
    </div>

    </div>

    <div style="float:left;">
    <h2>How does this work?</h2>
    <p>`img` can update its width based on its height while mainating the aspect ratio as defined by its intrinsic size. Using an SVG we create an image with intrinsic aspect ratio we want and rely on the browser to resize the width when height changes.</p>
    </div>

    <style>
    .parent {
    padding: 10px;
    height: 300px;
    background: green;
    animation-name: resize;
    animation-duration: 4s;
    animation-iteration-count: infinite;
    animation-direction: alternate;
    }

    .resizer {
    display: block;
    min-height:100%;
    width: auto;
    height: auto;
    }

    .wrapper {
    display: inline-block;
    height: 100%;
    position: relative;
    /* Chrome bug work-around.
    * See https://bugs.chromium.org/p/chromium/issues/detail?id=707151
    */
    /* padding-right: 0.0001%; */
    }

    .child {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: red;
    }
    @keyframes resize {
    from {height: 300px;}
    to {height: 150px;}
    }

    </style>