我正在处理图像,我遇到了纵横比问题。
<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。如何设置图像的大小,同时保持其纵横比。
当前回答
只需将高度属性替换为纵横比属性。
国际货币基金组织{最大宽度:500px;纵横比:900/600;}<img src=“big_image.png”width=“900”/>
纵横比属性不是必需的,但可以防止图像布局偏移。
其他回答
您可以创建如下div:
<div class="image" style="background-image:url('/to/your/image')"></div>
并使用此css设置其样式:
height: 100%;
width: 100%;
background-position: center center;
background-repeat: no-repeat;
background-size: contain; // this can also be cover
将图像容器标记的CSS类设置为图像类:
<div class="image-full"></div>
并将其添加到CSS样式表中。
.image-full {
background: url(...some image...) no-repeat;
background-size: cover;
background-position: center center;
}
您可以将容器设置为显示:伸缩和对齐项目:居中(其他对齐项目值也适用)。您也可以在图像本身上设置对齐自身,而不是对齐项目。
删除“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;"/>
要保持响应图像,同时仍然强制图像具有一定的纵横比,可以执行以下操作:
HTML格式:
<div class="ratio2-1">
<img src="../image.png" alt="image">
</div>
和SCSS:
.ratio2-1 {
overflow: hidden;
position: relative;
&:before {
content: '';
display: block;
padding-top: 50%; // ratio 2:1
}
img {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
}
无论作者上传的图像大小如何,这都可以用于强制执行特定的纵横比。
感谢@Ksesohttp://codepen.io/Kseso/pen/bfdhg.查看此URL以了解更多比率和工作示例。