css - 如何使用 CSS 填充图像并使其居中?
问题描述
我有一个任意形状和大小的图像,我想将其放大为包含 div 而不改变其比例并且不切断图像的一部分。
下面是我想到的图表:
请注意,图像有时垂直居中,有时水平居中。
如果图像总是很宽,我可以使用:
img {
width: 100%;
height: auto;
margin: auto;
}
但如果图像较窄,这将不起作用,因为它最终会切掉顶部和底部。
有没有办法,可能使用网格或 flex 来容纳图像?
解决方案
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.
推荐阅读
- cookies - 无法在 .net core 2.0 API 中设置和获取 Cookie
- blueprism - 可以在单个 VM 中安装多个 Blue Prism 运行时资源吗?
- python - 记录python更改日志级别文本
- php - 如何使用 preg_match_all 从字符串中获取单词
- javascript - 不明白我使用 parseFloat 时发生了什么
- vue.js - 在 Vue 模板中渲染表格
- c# - POST csv 文件 httpclient C# 和 application/x-www-form-urlencoded
- html - 使用 Ubuntu 时如何从 angular4 中删除哈希 (#)
- asp.net - Angular 5.2 使用 Asp.net core 2.1 更新到 Angular 6 Visual Studio mac 7.5.2
- r - Change the colour of a subset of labels in barplot R