如何在 CSS 中使用“object-fit: contains”并且图像上仍然有边框半径?

Mat*_*hew 6 html css image object-fit

我试图以“灯箱”样式显示图像,以便它将填充屏幕上的可用区域,在本例中为页面宽度的 90% 和高度的 70%。

使用object-fit: contain;似乎是做到这一点的事实上的方法,但它并不完全适用于border-radius. 是否可以在 上使用对象拟合<img>并且仍然按预期应用边界半径?

您需要调整浏览器窗口的大小,以查看运行以下代码片段时会发生什么。我在 JSFiddle 中运行了相同的代码,如下面的视频所示。

JSFiddle 视频演示

div {
  margin: auto;
  width: 90vw;
  height: 70vh;

  background-color: DeepSkyBlue;
}

img {
  width: 100%;
  height: 100%;
  object-fit: contain;

  border-radius: 50px;
  background-color: Crimson;
}
Run Code Online (Sandbox Code Playgroud)
<div>
  <img src="https://images.freeimages.com/images/large-previews/773/koldalen-4-1384902.jpg">
</div>
Run Code Online (Sandbox Code Playgroud)

A H*_*rth 5

遏制在这里并没有真正的帮助。

相反,将 img 的最大宽度和高度设置为 100%。系统会将其完全从上到下或从一侧到另一侧安装,但 img 元素将具有所需的任何尺寸,因此边框半径将正常工作。

要将 img 居中,如果这是您想要的,您可以将display: flex父 div 并将项目对齐/对齐到中心。

div {
  margin: auto auto;
  width: 90vw;
  height: 70vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: DeepSkyBlue;
}

img {
  max-width: 100%;
  max-height: 100%;

  border-radius: 50px;
  background-color: Crimson;
}
Run Code Online (Sandbox Code Playgroud)
<div>
  <img src="https://images.freeimages.com/images/large-previews/773/koldalen-4-1384902.jpg">
</div>
Run Code Online (Sandbox Code Playgroud)


G-C*_*Cyr 4

设置max-widthandmax-height似乎是您需要或期望的:

div {
  margin: auto;
  width: 90vw;
  height: 70vh;
  display:grid;

  background-color: DeepSkyBlue;
}

img {
  max-width: 100%;
  max-height: 100%; 
  margin:auto;/* x,y center if inside a grid or flex box */
 
  object-fit: contain;/* useless by now, img should keep its ratio */
  border-radius: 50px;
  border-radius: calc( 5vw + 5vh); /* will scale, maybe you find this usefull */
  background-color: Crimson;
}
Run Code Online (Sandbox Code Playgroud)
<div>
  <img src="https://images.freeimages.com/images/large-previews/773/koldalen-4-1384902.jpg">
</div>
Run Code Online (Sandbox Code Playgroud)