【问题标题】:CSS aspect-ratio not working properly in FirefoxCSS 纵横比在 Firefox 中无法正常工作
【发布时间】:2022-01-06 13:22:18
【问题描述】:

我创建了一个简单的 div,将纵横比属性设置为另一个 div 的子级。内部 div 必须填充整个可能的空间(但仍然尊重通过的纵横比)。

它在基于 chromium 的浏览器上按预期工作,但在 Firefox 上,当设置 width: 100% 并且内部 div 最终被拉伸时,它似乎忽略了纵横比。

.box {
  width: 100%;
  max-height: 100%;
  aspect-ratio: 1 / 1;
  border: 2px dashed black;
  background-color: lightblue;
}

.container {
  height: 50vh;
}
<div class="container">
  <div class="box">
    Sample content
  </div>
</div>

【问题讨论】:

  • 如果不希望宽度为 100%,为什么要将宽度设置为 100%?
  • @xdumaine 我希望它是 100% 宽,只要没有达到最大高度。

标签: css firefox aspect-ratio


【解决方案1】:

aspect-ratioweak declaration,因此您在 Firefox 中得到的内容可以被认为是正确的,因为该元素在 aspect-ratio 之前尊重 widthmax-height。我什至会说 Chrome 的行为是错误的。

值得注意的是,aspect-ratio 只设置了一个首选纵横比 ref,以提供与具有固有纵横比的图像元素类似的行为。它从来没有打算强制元素的比例。

在您的示例中使用图像,您将获得与在 Firefox 中相同的结果

.box {
  width: 100%;
  max-height: 100%;
  /*aspect-ratio: 1 / 1;*/
}

.container {
  height: 50vh;
}
<div class="container">
  <img src="https://picsum.photos/id/237/300/300" class="box">
</div>

以上将为您提供一个拉伸图像,以确认 Firefox 的正确行为

【讨论】:

    【解决方案2】:

    使用 max-width: 100% 代替,在 chrome 和 firefox 中对我来说效果很好:

    .box {
      max-width: 100%;
      max-height: 100%;
      aspect-ratio: 1 / 1;
      border: 2px dashed black;
      background-color: lightblue;
    }
    
    .container {
      height: 50vh;
    }
    <div class="container">
      <div class="box">
        Sample content
      </div>
    </div>

    【讨论】:

      猜你喜欢
      • 2013-07-18
      • 1970-01-01
      • 2014-03-30
      • 2021-12-24
      • 2023-03-31
      • 1970-01-01
      • 2014-02-05
      • 1970-01-01
      • 2014-08-18
      相关资源
      最近更新 更多