我正在处理图像,我遇到了纵横比问题。
<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。如何设置图像的大小,同时保持其纵横比。
当前回答
您可以创建如下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
其他回答
国际货币基金组织{最大宽度:80px;/*也适用于百分比值,如100%*/高度:自动;}<p>此图像最初为400x400像素,但应通过CSS调整大小:</p><img width=“400”height=“400”src=“https://i.stack.imgur.com/aEEkn.png"><p>假设HTML的作者故意想要高度为宽度值的一半,此CSS将忽略HTML作者的愿望,这可能是您想要的,也可能不是您想要的:</p><img width=“400”height=“200”src=“https://i.stack.imgur.com/aEEkn.png">
删除“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;"/>
您可以使用此选项:
img {
width: 500px;
height: 600px;
object-fit: contain;
position: relative;
top: 50%;
transform: translateY(-50%);
}
这是精神上的。使用比例缩小属性-它可以自行解释。
内联样式:
<img src='/nic-cage.png' style={{ maxWidth: '50%', objectFit: 'scale-down' }} />
这将阻止flex拉伸它。在这种情况下,图像将达到其父容器宽度的50%,并且高度将缩小以匹配。
保持简单。
这里有一个解决方案:
object-fit: cover;
width: 100%;
height: 250px;
您可以调整宽度和高度以满足您的需要,对象拟合属性将为您进行裁剪。
有关对象拟合属性和兼容性表的可能值的更多信息,请参见:https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit