cssheightwidthaspect-ratio

Set div height to half the width minus 50px


To make my div’s height equal to its width, I use aspect-ratio. For example:

width: calc((100% / 5) - 8px);
aspect-ratio: 1;

Now, I want the height to be half the width minus 50px. I can’t just use calc() inside aspect-ratio. Is there an efficient way to achieve this without using JavaScript or viewport units (like vw)?

Thank you!


Solution

  • It's a bit unconventional, but using padding-bottom might work well.

    .example {
      --width: calc((100% / 5) - 8px);
      width: var(--width);
      padding-bottom: calc(var(--width) / 2 - 50px);
      background-color: #555;
    }
    <div class="example"></div>

    Thinking about edge cases, you can ensure that the padding-bottom value is at least (e.g.) 10px, even if the calculation width/2 - 50px results in 10, zero, or a negative value.

    .example {
      --width: calc((100% / 5) - 8px);
      width: var(--width);
      padding-bottom: max(calc(var(--width) / 2 - 50px), 10px);
      background-color: #555;
    }
    <div class="example"></div>