image - 保持图像纵横比
问题描述
我目前正在重构我的网站并尝试摆脱一些断点。在我的投资组合中,我有一个图片库,其中显示 3x3 的图片拼贴。这些图块是用 css 网格构建的。我的示例中的图块应为 200 像素高和最小最大(200 像素,333 像素)宽度。
目前,瓷砖按预期工作。但是图像不保持它们的纵横比。有什么办法可以保持原始比例并将图像剪切到它们的高度?容器的最小版本应该是 200x200。
https://codepen.io/yanniksturm/pen/LYVegro
<div class="content">
<div id="img1" class="imageWrapper">
<img src="https://images.unsplash.com/photo-1562886889-4ff7af0602ef?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2089&q=80">
</div>
<div id="img2" class="imageWrapper">
<img src="https://images.unsplash.com/photo-1562886889-4ff7af0602ef?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2089&q=80">
</div>
<div id="img3" class="imageWrapper">
<img src="https://images.unsplash.com/photo-1562886889-4ff7af0602ef?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2089&q=80">
</div>
</div>
.content {
min-width: 600px;
max-width: 999px;
margin: auto;
width: 80%;
backgeound-color: red;
display: grid;
grid-template-columns: minmax (200px, 333px) minmax (200px, 333px) minmax (200px, 333px);
grid-template-rows: 200px;
}
.imageWrapper {
height: 100%;
width: 100%;
}
img {
height: 100%;
width: 100%;
}
#img1 {
grid-column: 1;
}
#img2 {
grid-column: 2;
}
#img3 {
grid-column: 3;
}
非常感谢你的帮助!
解决方案
您需要将img
宽度和高度设置为auto
并添加一个max-width: 100%;
以保持纵横比。
img {
height: auto;
width: auto;
max-width: 100%;
}
请参见下面的片段。
您可以使用object-fit: cover;
,但旧浏览器不支持(我正在查看 IE11)。
.content {
min-width: 600px;
max-width: 999px;
margin: auto;
width: 80%;
backgeound-color: red;
display: grid;
grid-template-columns: minmax (200px, 333px) minmax (200px, 333px) minmax (200px, 333px);
grid-template-rows: 200px;
}
.imageWrapper {
height: 100%;
width: 100%;
border: 1px solid red;
}
img {
height: auto;
width: auto;
max-width: 100%;
}
#img1 {
grid-column: 1;
}
#img2 {
grid-column: 2;
}
#img3 {
grid-column: 3;
}
<div class="content">
<div id="img1" class="imageWrapper">
<img src="https://images.unsplash.com/photo-1562886889-4ff7af0602ef?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2089&q=80">
</div>
<div id="img2" class="imageWrapper">
<img src="https://images.unsplash.com/photo-1562886889-4ff7af0602ef?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2089&q=80">
</div>
<div id="img3" class="imageWrapper">
<img src="https://images.unsplash.com/photo-1562886889-4ff7af0602ef?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2089&q=80">
</div>
</div>
推荐阅读
- discord.js - 全球禁令不包括某些服务器 Discord.JS
- laravel - 结帐付款后如何处理 webhook 内部的错误
- javascript - 反应滑块防止图像在更改时重新加载
- php - 将参数传递给 WordPress 中的短代码函数
- docker - AWS Codebuild 仅在未进行任何更改时使用缓存的 Docker 层
- rust - 切换可选的构建依赖项和使用功能构建依赖项
- cron - 用于在 Apache Airflow 中安排自触发 DAG 的 crontab 表达式
- sql - 如何在 Group By 查询中显示零值
- spring-boot - 为 Spring Boot 应用程序实现状态管理
- cmake - 如何强制 cmake 不配置依赖目录?