所以我想要一个img
尽可能大地显示,
- 在横向时充满整个宽度,在纵向时充满整个高度
- 没有裁剪
- 没有倾斜或拉伸(保持原始纵横比)
- 垂直和水平居中
此外,图片的原始尺寸是未知的。
我已经尝试了不少方案来实现这一点,包括使用 flexbox(为了获取垂直居中),但没有一种方法可以完全符合所有条件。
理想情况下,当然希望这是一个全 CSS 解决方案,但我也一直在研究一些 JS 方案。
谢谢
所以我想要一个img
尽可能大地显示,
此外,图片的原始尺寸是未知的。
我已经尝试了不少方案来实现这一点,包括使用 flexbox(为了获取垂直居中),但没有一种方法可以完全符合所有条件。
理想情况下,当然希望这是一个全 CSS 解决方案,但我也一直在研究一些 JS 方案。
谢谢
max-width
和max-height
都为100%
。object-fit
。
.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;" >
zoom: 10
(10应该足够),以使图像更小。 - Pandaiolomax-height
和max-width
不能增加图像的尺寸。如果您的图像很小,它们将保持小。原帖作者要求图像能够缩放以填充视口。 - Xavierdiv
,并使用这个CSS3属性:background-size: contain
contain值指定了无论包含盒子的大小如何,背景图像都应该缩放,使得每一边尽可能大而不超过容器相应边的长度。请记住,如果
div
大于您的原始图像,则您的图像将被放大。img
标记。如果你像我一样,那么你希望你的图片能够被搜索引擎优化,并且在社交媒体中嵌入链接时能够展现出所有酷炫的效果。 - Xavier只需像这样设置图像的默认CSS:
img {
width:auto;
height:auto;
max-width:100%;
max-height:100%;
}
@media (orientation: landscape) { img { height:100%; } }
@media (orientation: portrait) { img { width:100%; } }
div
设置为100%宽度和高度,如下所示:div.parent {
display:flex;
position:fixed;
left:0px;
top:0px;
width:100%;
height:100%;
justify-content:center;
align-items:center;
}
display
设置为flex
,元素现在已准备好使用弹性盒模型。 justify-content
属性设置弹性项的水平对齐方式。 align-items
属性设置弹性项的垂直对齐方式。经过多次尝试,我发现这解决了我的问题。它用于通过浏览器在电视上显示照片。
唯一需要注意的是非常宽的图像。它们会被拉伸填充,但不会太多,标准相机照片不会改变。
试一试吧 :)
*目前仅在Chrome中进行了测试
HTML:
<div class="frame">
<img src="image.jpg"/>
</div>
.frame {
border: 1px solid red;
min-height: 98%;
max-height: 98%;
min-width: 99%;
max-width: 99%;
text-align: center;
margin: auto;
position: absolute;
}
img {
border: 1px solid blue;
min-height: 98%;
max-width: 99%;
max-height: 98%;
width: auto;
height: auto;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
yourimg {
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 100%;
}
并确保其中没有带有 position: relative 属性的父级标签