当flex-direction设置为column时,如何将flex容器中元素的长宽比固定为1?

问题描述 投票:0回答:1

我的 Flex 容器中有多个元素(本例中为 3 个,但我希望它适用于任意数量的元素)。 它们在宽屏幕上排列成行,在窄屏幕上排列成列。 每个元素都包含一个 svg。 我希望 svg 的内容的纵横比为 1。 我的代码在宽屏幕上运行良好,但在窄屏幕上运行不佳。 在窄屏幕上,当宽高比设置为 1 时,元素的高度不再受到 Flex 容器的限制。 我对这种行为感到非常困惑,我想了解原因。另外,我很想知道如何做才能在容器中包含三个垂直 div,而其中每个 svg 的长宽比均为 1。

这是我的代码的一个简单示例:

<style>
        .container-test{
            height:30vh;
            display:flex;
            flex-direction: row;
        }

        .col-test{
            flex:1;
            max-height:100%;}

        .wrapper{
            position:relative;
            display:block;
            max-height: 100%;
            max-width:100%;
            aspect-ratio: 1;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }

        .graph{
            display:block;
            height:100%;
            width:100%;
        }

        @media (max-width: 576px) {
            .container-test{
                flex-direction: column;
            }
        }
    </style>

    <div class="container-test">
        <div class="col-test">
            <div class="wrapper" >
                <svg class="graph" style="background-color:yellow; "> </svg>
            </div>
        </div>
        <div class="col-test">
            <div class="wrapper" >
                <svg class="graph" style="background-color:blue; "></svg>
            </div>
        </div>
        <div class="col-test">
            <div class="wrapper" >
                <svg class="graph" style="background-color:green;"></svg>
            </div>
        </div>
    </div>

如果我对 .col-test 的高度进行硬编码(例如将其设置为 33%),我就可以使其工作。不过,我希望有一个更简洁的解决方案,我可以轻松地重复使用任意数量的元素。

css flexbox aspect-ratio
1个回答
0
投票

您可以将 min-height 添加到 .col-test

<style>
  .container-test {
    height: 30vh;
    display: flex;
    flex-direction: row;
  }

  .col-test {
    flex: 1;
    max-height: 100%;
    min-height: 0;
  }

  .wrapper {
    position: relative;
    display: block;
    max-height: 100%;
    max-width: 100%;
    aspect-ratio: 1;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    flex-shrink: 0;
  }

  .graph {
    display: block;
    height: 100%;
    width: 100%;
  }

  @media (max-width: 576px) {
    .container-test {
      flex-direction: column;
    }
  }
</style>
<div class="container-test">
  <div class="col-test">
    <div class="wrapper">
      <svg class="graph" style="background-color: yellow"></svg>
    </div>
  </div>
  <div class="col-test">
    <div class="wrapper">
      <svg class="graph" style="background-color: blue"></svg>
    </div>
  </div>
  <div class="col-test">
    <div class="wrapper">
      <svg class="graph" style="background-color: green"></svg>
    </div>
  </div>
</div>

© www.soinside.com 2019 - 2024. All rights reserved.