是否有一种纯CSS的方法可以将图像缩放到边界框中(保持长宽比)?如果图像大于容器,则可以使用此方法:
img {
max-width: 100%;
max-height: 100%;
}
示例:
- 用例1(正常工作):http://jsfiddle.net/Jp5AQ/2/
- 用例2(正常工作):http://jsfiddle.net/Jp5AQ/3/
但我想将图像缩放到某个维度以达到容器的100%。
- 用例3(不起作用):http://jsfiddle.net/Jp5AQ/4/
是否有一种纯CSS的方法可以将图像缩放到边界框中(保持长宽比)?如果图像大于容器,则可以使用此方法:
img {
max-width: 100%;
max-height: 100%;
}
示例:
但我想将图像缩放到某个维度以达到容器的100%。
我使用表格将图像居中放置在盒子内。它保持纵横比,并以完全符合盒子的方式缩放图像。如果图像小于盒子,则会在中心显示。以下代码使用40px宽度和40px高度的盒子。(不太确定它的效果,因为我从另一个更复杂的代码中删除了它并稍微简化了一下)
.SmallThumbnailContainer {
display: inline-block;
position: relative;
float: left;
width: 40px;
height: 40px;
border: 1px solid #ccc;
margin: 0px;
padding: 0px;
}
.SmallThumbnailContainer {
width: 40px;
margin: 0px 10px 0px 0px;
}
.SmallThumbnailContainer tr {
height: 40px;
text-align: center;
}
.SmallThumbnailContainer tr td {
vertical-align: middle;
position: relative;
width: 40px;
}
.SmallThumbnailContainer tr td img {
overflow: hidden;
max-height: 40px;
max-width: 40px;
vertical-align: middle;
margin: -1px -1px 1px -1px;
}
<table class="SmallThumbnailContainer" cellpadding="0" cellspacing="0">
<tr>
<td>
<img src="https://www.gravatar.com/avatar/bf7d39f4ed9c289feca7de38a0093250?s=32&d=identicon&r=PG" width="32" height="32" alt="OP's SO avatar image used as a sample jpg because it is hosted on SO, thus always available" />
</td>
</tr>
</table>
这对我的需求很有效,它在设置高度限制时不会压缩图像,而是会溢出。
.top-container{
width:50%;
}
.img-container {
display: flex;
justify-content: center;
align-items: center;
height: 40vh;
width: 100%;
overflow: hidden;
}
.img-container img {
max-width: 10%;
max-height: auto;
transform: scale(10);
}
<div class='top-container'>
<div class='img-container'>
<img src='image.jpg'>
</div>
</div>
<div class="box"><img src="image.jpg"></div>
.box {height: auto;
object-fit: cover;}
img { height: 100%; object-fit: cover; }
.img-class {
width: <img width>;
height: <img height>;
content: url('/path/to/img.png');
}
然后在元素上(您可以使用JavaScript或媒体查询来添加响应性):
<div class='img-class' style='transform: scale(X);'></div>
.boundingbox {
width: 400px;
height: 500px;
border: 2px solid #F63;
}
img{
width:400px;
max-height: 500px;
height:auto;
}
<div class="boundingbox"><img src="image.jpg"/></div>