使具有自然尺寸的图像适合父容器最大高度约束(无对象拟合)

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

我有一个图像,其高度应受到限制,因此容器高度最大为 400px。图像应保持其自然的长宽比。

重要的是,我不能使用

object-fit
,因为我想提供图像
border-radius

我正在寻找一种适用于所有现代浏览器的无 JS 解决方案。我找到了一个使用 CSS 网格的非常简单的解决方案,但它仅适用于 Firefox。

// Solution should not use Javascript.
// Below is simply to rotate images for testing.

const heights = [100, 200, 300, 400, 1000, 2000]
const widths = [200, 350, 1200]

let wIndex = 0, hIndex = 0;

setInterval(() => {
  hIndex = (hIndex + 1) % heights.length;
  wIndex = (wIndex + 1) % widths.length;

  const h = heights[hIndex];
  const w = widths[wIndex];

  document.querySelector("img").src = `https://placehold.co/${w}x${h}`;
}, 1_000)
.container {
  display: flex;
  flex-direction: column;
  width: 400px;

  max-height: 400px; /* I want to constrain entire container to 400px tall */

  border: 3px solid rebeccapurple;
}

img {
  /* Because I want to round corners of image, cannot use object-fit */
  border-radius: 16px;
}

/* ------ FIREFOX SOLUTION BELOW -------
 *
 * The below only works in Firefox
 */
.img-container {
  display: grid;
  min-height: 0;
}

img {
  margin: auto;
  height: 100%;
  max-width: 100%;
}
<p>Rebeccapurple container has max height of 400px.</p>

<div class="container">
  <div class="img-container">
    <img>
  </div>

  <p>This text is some more content of arbitrary height and should not be pushed out of container</p>
</div>

请参阅以下我正在寻找的结果的演示(在 Firefox 中):

html css grid
1个回答
0
投票

您可以使用弹性盒和绝对定位的组合来实现这一点。这是一个简单的 HTML 和 CSS 设置:

.container {
  position: relative;
  width: 400px;
  max-height: 400px;
  border: 3px solid rebeccapurple;
  overflow: hidden;
}

.img-container {
  position: relative;
  width: 100%;
  height: 0;
  padding-bottom: 100%; /* Maintain aspect ratio */
  overflow: hidden;
}

img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border-radius: 16px;
}
<p>The purple container has a maximum height of 400px.</p>

<div class="container">
  <div class="img-container">
    <img src="https://placehold.co/200x100">
  </div>

  <p>This text is additional content with an arbitrary height and should not be pushed out of the container.</p>
</div>

此解决方案可确保图像保持其纵横比、具有圆角,并且适用于所有现代浏览器。

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