Search code examples
cssresponsive-designaspect-ratio

Maintain div aspect ratio according to height


I need to maintain the width of an element as a percentage of its height. So as the height changes, the width is updated.

The opposite is achievable by using a % value for padding-top, but padding-left as a percentage will be a percentage of the width of an object, not its height.

So with markup like this:

<div class="box">
  <div class="inner"></div>
</div>

I'd like to use something like this:

.box {
    position: absolute;
    margin-top: 50%;
    bottom: 0;
}
.inner {
    padding-left: 200%;
}

To ensure the box's aspect ratio is maintained according to it's height. The height is fluid because of it's % margin - as the window's height changes, the box's height will too.

I know how to achieve this with JavaScript, just wondering if there's a clean CSS-only solution?


Solution

  • You can simply use the aspect-ratio property:

    .box {
      height: 50%;
      background-color: #3CF;
      aspect-ratio: 2 /1;
    }
    /* for demo only */
    body {
      font: medium sans-serif;
    }
    ul {
      margin: 0;
      padding-top: 1em;
      padding-bottom: 1em;
    }
    .demo {
      width: 90vw;
      height: 90vh;
      overflow: auto;
      resize: both;
      outline: 1px solid #999;
    }
    <div class="demo">
      <div class="box">
        <ul>
          <li>This box has fluid height of 50%</li>
          <li>It has an aspect ratio of 2:1</li>
          <li>Resize the container vertically (or horizontally)</li>
          <li>The box will maintain its aspect ratio</li>
          <li>The text content will not affect its width</li>
        </ul>
      </div>
    </div>