我正在处理图像,我遇到了纵横比问题。
<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。如何设置图像的大小,同时保持其纵横比。
当前回答
将图像容器标记的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;"/>
https://jsfiddle.net/sot2qgj6/3/
如果你想用固定的宽度百分比,而不是固定的宽度像素来放置图像,这就是答案。
这在处理不同大小的屏幕时很有用。
诀窍是
使用padding top设置高度与宽度之间的距离。使用position:absolute将图像放入填充空间。使用最大高度和最大宽度确保图像不会覆盖父元素。使用display:block和margin:auto将图像居中。
我也评论了小提琴中的大部分技巧。
我还找到了其他方法来实现这一点。在html中不会有真实的图像,所以当我需要html中的“img”元素时,我个人更倾向于首选答案。
使用背景的简单csshttp://jsfiddle.net/4660s79h/2/
顶部有单词的背景图像http://jsfiddle.net/4660s79h/1/
使用位置绝对值的概念如下http://www.w3schools.com/howto/howto_css_aspect_ratio.asp
您可以使用此选项:
img {
width: 500px;
height: 600px;
object-fit: contain;
position: relative;
top: 50%;
transform: translateY(-50%);
}
这里有一个解决方案:
img {
width: 100%;
height: auto;
object-fit: cover;
}
这将确保图像始终覆盖整个父对象(向下和向上缩放)并保持相同的纵横比。
将图像容器标记的CSS类设置为图像类:
<div class="image-full"></div>
并将其添加到CSS样式表中。
.image-full {
background: url(...some image...) no-repeat;
background-size: cover;
background-position: center center;
}