响应式图像全屏居中 - 保持纵横比,不超过窗口 [英] Responsive Image full screen and centered - maintain aspect ratio, not exceed window
问题描述
所以我想显示一个 img
- 尽可能大(横向时填充宽度/纵向时填充高度)
- 没有裁剪
- 无歪斜或拉伸(原始纵横比)
- 垂直和水平居中
此外,图片的原始尺寸未知.
Also, the image's original size is not known.
为此我尝试了很多不同的选项,包括一个 flexbox 选项(以获得垂直中心),但似乎没有任何选项可以满足所有条件.
I've tried quite a few different options for this, including a flexbox one (to get the vertical center), but nothing seems to tick all the boxes.
理想情况下,我当然希望这是一个全 CSS 解决方案,但我也一直在研究一些 JS.
Ideally I'd like this to be an all CSS solution of course, but I have been looking into some JS as well.
谢谢
推荐答案
要将其居中,您可以使用此处显示的技术:绝对居中.
To center it, you can use the technique shown here: Absolute centering.
为了让它尽可能大,给它max-width
和max-height
的100%
.
To make it as big as possible, give it max-width
and max-height
of 100%
.
要保持纵横比(即使像下面的代码段那样专门设置了宽度),请使用 object-fit
如此处.
To maintain the aspect ratio (even when the width is specifically set like in the snippet below), use object-fit
as explained here.
.className {
max-width: 100%;
max-height: 100%;
bottom: 0;
left: 0;
margin: auto;
overflow: auto;
position: fixed;
right: 0;
top: 0;
-o-object-fit: contain;
object-fit: contain;
}
<img src="https://i.imgur.com/HmezgW6.png" class="className" />
<!-- Slider to control the image width, only to make demo clearer !-->
<input type="range" min="10" max="2000" value="276" step="10" oninput="document.querySelector('img').style.width = (this.value +'px')" style="width: 90%; position: absolute; z-index: 2;" >
这篇关于响应式图像全屏居中 - 保持纵横比,不超过窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!