我正在处理图像,我遇到了纵横比问题。
<img src="big_image.jpg" width="900" height="600" alt="" />
如您所见,高度和宽度已经指定。我为图像添加了CSS规则:
img {
max-width: 500px;
}
但对于big_image.jpg,我得到的宽度=500,高度=600。如何设置图像的大小,同时保持其纵横比。
我正在处理图像,我遇到了纵横比问题。
<img src="big_image.jpg" width="900" height="600" alt="" />
如您所见,高度和宽度已经指定。我为图像添加了CSS规则:
img {
max-width: 500px;
}
但对于big_image.jpg,我得到的宽度=500,高度=600。如何设置图像的大小,同时保持其纵横比。
当前回答
您可以将容器设置为显示:伸缩和对齐项目:居中(其他对齐项目值也适用)。您也可以在图像本身上设置对齐自身,而不是对齐项目。
其他回答
使用伪元素进行垂直对齐怎么样?这更少的代码用于旋转木马,但我想它适用于每个固定大小的容器。它将保持纵横比,并在顶部/底部或左侧/写入最短尺寸时插入@灰色暗条。同时,图像通过文本对齐水平居中,通过伪元素垂直居中。
> li {
float: left;
overflow: hidden;
background-color: @gray-dark;
text-align: center;
> a img,
> img {
display: inline-block;
max-height: 100%;
max-width: 100%;
width: auto;
height: auto;
margin: auto;
text-align: center;
}
// Add pseudo element for vertical alignment of inline (img)
&:before {
content: "";
height: 100%;
display: inline-block;
vertical-align: middle;
}
}
要强制图像符合精确的大小,您不需要编写太多代码。太简单了
国际货币基金组织{宽度:200px;高度:自动;对象拟合:包含;/*按图像大小调整徽标*/-o-object-fit:contain;/*为opera浏览器安装徽标*/对象位置:顶部;/*设置徽标位置*/-o对象位置:顶部;/*opera浏览器的徽标位置*/}<img src=“http://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.png“alt=”徽标“>
全屏演示:
img[data-attribute] {height: 100vh;}
请记住,如果观察端口高度大于图像,则图像将相对于差异自然降级。
与这里的一些答案非常相似,但在我的案例中,我的图像有时更高,有时更大。
这种风格就像一种魅力,确保所有图像都使用所有可用空间,保持比例而不是剪切:
.img {
object-fit: contain;
max-width: 100%;
max-height: 100%;
width: auto;
height: auto;
}
删除“height”属性。
<img src="big_image.jpg" width="900" alt=""/>
通过指定这两个选项,可以更改图像的纵横比。只需设置一个即可调整大小,但保持纵横比。
(可选)限制过大:
<img src="big_image.jpg" width="900" alt="" style="max-width:500px; height:auto; max-height:600px;"/>