【问题标题】:Force image to stay between height & width "boundaries", as well as keep aspect ratio强制图像保持在高度和宽度“边界”之间,并保持纵横比
【发布时间】:2020-03-04 16:08:30
【问题描述】:

我希望将图像保持在最小和最大高度和宽度之间,同时尊重纵横比(所以如果需要缩小图像,它会缩小保持纵横比,直到宽度和高度参数低于给定的max-widthmax-height)

它尝试了以下css:

.box {
  min-width: 128px;
  min-height: 128px;
  width: auto;
  height: auto;
  max-width: 100%;
  max-height: 256px;
  display: flex;
}

.inner {
  background-color: cyan;
  width: 100%;
  height: 100%;
  display: block;
  object-fit: contain;
}
<div class="box">
<img class="inner" src="https://i.imgur.com/3t7YAt8.png"/>
</div>

但是,当直接在上面运行时,max-height 会被忽略,图像只遵循max-width 约束。 (可以通过修改max-width来显示,图片会这样缩放)。

如果我将图像本身的 css 更改为使用 max-widthmax-height 而不是宽度/高度属性,则图像不再缩放以保持纵横比。

.box {
  min-width: 128px;
  min-height: 128px;
  width: auto;
  height: auto;
  max-width: 100%;
  max-height: 256px;
  display: flex;
}

.inner {
  background-color: cyan;
  max-width: 100%;
  max-height: 100%;
  display: block;
  object-fit: contain;
}
<div class="box">
<img class="inner" src="https://i.imgur.com/3t7YAt8.png"/>
</div>

附带说明:在示例中,图像是正方形,但并非总是如此。

【问题讨论】:

    标签: html css scale


    【解决方案1】:

    为了使图像保持纵横比,请使用 css 属性“object-fit: contains;”在图片标签上

    【讨论】:

    • 虽然这确实可以防止重新缩放的图像失去纵横比,但它也无助于 div 的实际缩放:图像仍然“占用”最大宽度,而不是推动“其他”内容到双方。 (如青色矩形所示)。
    【解决方案2】:

    .box {
      min-width: 128px;
      min-height: 128px;
      width: auto;
      height: auto;
      max-width: 100%;
      max-height: 256px;
      position: relative
    }
    
    .inner {
      background-color: cyan;
      width: auto;
      height: 100%;
      display: block;
      object-fit: contain;
      position:absolute;
    }
    <div class="box">
    <img class="inner" src="https://i.imgur.com/3t7YAt8.png"/>
    </div>

    【讨论】:

    • 不,背景应该和图片一样大。青色区域我希望现在是一个正方形。
    • 现在它固定在最小尺寸;而不是最多填充 256 个像素。
    猜你喜欢
    • 2014-07-01
    • 2019-11-14
    • 1970-01-01
    • 2016-05-18
    • 1970-01-01
    • 2018-09-28
    • 2021-06-23
    • 2021-02-09
    • 2014-02-06
    相关资源
    最近更新 更多