首页 > 解决方案 > 如何使用 CSS 填充图像并使其居中?

问题描述

我有一个任意形状和大小的图像,我想将其放大为包含 div 而不改变其比例并且不切断图像的一部分。

下面是我想到的图表:

在此处输入图像描述

在此处输入图像描述

请注意,图像有时垂直居中,有时水平居中。

如果图像总是很宽,我可以使用:

img {
    width: 100%;
    height: auto;
    margin: auto;
}

但如果图像较窄,这将不起作用,因为它最终会切掉顶部和底部。

有没有办法,可能使用网格或 flex 来容纳图像?

标签: cssimage

解决方案


Use object-fit: contain for the img selector in the css,

  • your <img> tag will be your gray frame like in above.
  • the real picture will be hosted as you wish no matter what the intrinsic size of the image is and the size of the <img> tag is.

推荐阅读