0

Really can't find a solid answer for if this is possible.

I have a flexbox container with a dynamic height and dynamic number of flex items. I want the flex items to evenly fill the height and then set the width at a given aspect ratio (1/1 in my case) to the calculated height of the flex item.

I know there are tricks for the (width -> height) but haven't seen a solid answer for the other way round. I am using sass if that helps. Then js (react) as last resort. Thanks!

.flex-container {
  /* height could be anything dynamic */
  height: 80vh;
  display: flex;
  flex-direction: column;
  /* so we can see the items better */
  gap: 10px;
  /* width shouldn't static but set to an aspect ratio of height */
  width: 50px;
}

.item {
  flex: 1;
  background-color: aqua;
}
<div class="flex-container">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div>
Luke
  • 323
  • 4
  • 11

1 Answers1

0

Depending on your need of retrocompatibility, you could use the css property aspect-ratio.

aspect-ratio

The aspect-ratio CSS property sets a preferred aspect ratio for the box, which will be used in the calculation of auto sizes and some other layout functions.
Source: MDN

It's implemented in all browsers' latest versions. See caniuse.com.

.flex-container {
  /* height could be anything dynamic */
  height: 80vh;
  display: flex;
  flex-direction: column;
  /* so we can see the items better */
  gap: 10px;
  align-items: flex-start; /* By using align-items, you make sure that your .item won't stretch */
}

.item {
  flex: 1;
  background-color: aqua;
  aspect-ratio: 1/1; /* Adds aspect-ratio */
}
<div class="flex-container">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div>
Amaury Hanser
  • 3,191
  • 12
  • 30
  • Thanks, I had looked at aspect ratio but was hoping to for an alternative as it's not quite widespread enough for my liking yet. – Luke Nov 09 '21 at 11:17