保持可缩放图像的纵横比
Maintaining the aspect ratio of a scalable image
我正在使用 css 属性 转换:translateY 将图像在页面上垂直居中。图片的宽度是页面宽度的百分比,因此如果用户放大或缩小浏览器,它会被缩放 window。
这是标记:
<div class="item">
<img src="..." width="50%">
</div>
这里是 css:
.item {
width: 100%;
height: 100%;
text-align: center;
}
div.item > img {
max-height: 100%;
max-width: 100%;
position: relative;
top: 50%;
transform: translateY(-50%);
}
这非常有效,除非浏览器 window 比宽度短很多,在这种情况下,图像的高度会被修剪,或者通过将图像的最大高度设置为 100%,被压缩.在观看此演示时,您可以通过大幅降低浏览器 window 的高度来发现问题:https://jsfiddle.net/0zh4qvLm/。在这种情况下如何保持图像的纵横比?
在你的 max-width
下添加 width: auto
。 JS Fiddle
div.item > img {
max-height: 100%;
max-width: 100%;
width: auto;
position: relative;
top: 50%;
transform: translateY(-50%);
-webkit-transform: translateY(-50%);
}
将您的 CSS 更改为
div.item > img {
max-height: 100%;
max-width: 50%;
width:auto;
position: relative;
top: 50%;
transform: translateY(-50%);
-webkit-transform: translateY(-50%);
}
并从您的 <img>
中删除 width
属性
我正在使用 css 属性 转换:translateY 将图像在页面上垂直居中。图片的宽度是页面宽度的百分比,因此如果用户放大或缩小浏览器,它会被缩放 window。
这是标记:
<div class="item">
<img src="..." width="50%">
</div>
这里是 css:
.item {
width: 100%;
height: 100%;
text-align: center;
}
div.item > img {
max-height: 100%;
max-width: 100%;
position: relative;
top: 50%;
transform: translateY(-50%);
}
这非常有效,除非浏览器 window 比宽度短很多,在这种情况下,图像的高度会被修剪,或者通过将图像的最大高度设置为 100%,被压缩.在观看此演示时,您可以通过大幅降低浏览器 window 的高度来发现问题:https://jsfiddle.net/0zh4qvLm/。在这种情况下如何保持图像的纵横比?
在你的 max-width
下添加 width: auto
。 JS Fiddle
div.item > img {
max-height: 100%;
max-width: 100%;
width: auto;
position: relative;
top: 50%;
transform: translateY(-50%);
-webkit-transform: translateY(-50%);
}
将您的 CSS 更改为
div.item > img {
max-height: 100%;
max-width: 50%;
width:auto;
position: relative;
top: 50%;
transform: translateY(-50%);
-webkit-transform: translateY(-50%);
}
并从您的 <img>
width
属性