首页 > 解决方案 > 如何保持与图像的比例?

问题描述

我有 3 张图像: 1- 320 x 420 2- 600 x 450 3- 695 x 355

我怎样才能使用 css 和 html 为所有三个图像提供 260 x 260 的尺寸?我不想剪切图像,我想保持它们的原始比例。谢谢你的帮助

标签: css

解决方案


object-fit是为此而设计的,它将保持比例,还可以按照您想要的方式剪辑您的图像:

CSS 属性设置如何调整替换元素的object-fit内容,例如<img>or <video>,以适应其容器。

语法值:fill | contain | cover | none | scale-down

object-position您可以使用该属性更改被替换元素的内容对象在元素框内的对齐方式。前任 :

img[class] {
width:260px;
height:260px;
object-fit:cover;
}
img:nth-child(1) {
object-position: center top;
}
img:nth-child(3) {
object-position: right top;
}
<img class src=https://placeimg.com/320/420/animals>
<img class src=https://placeimg.com/600/450/animals>
<img class src=https://placeimg.com/695/355/animals>
<p>Original size</p>
<img  src=https://placeimg.com/320/420/animals>
<img  src=https://placeimg.com/600/450/animals>
<img  src=https://placeimg.com/695/355/animals>

如果你的图片只是设计的一部分,那么background-image,background-size,background-position可以做类似的视觉效果。


推荐阅读