我知道 HTML 图像的宽度和高度属性可以通过 <img src="Debian.jpg" style="height: 120px; width: 130px">
简单地设置。 .
我正在寻找的是是否存在一个在 %
中只取一个值的 CSS 属性。并根据该百分比缩放原始图像的宽度和高度。例如,如果 Debian.jpg
的高度和宽度是 1000x700
我指定 50%
在那个 CSS 属性中,图像缩小到 500x350
因此保持纵横比。
我很难在单独调整高度和宽度的同时保持图像的纵横比。如果不存在这样的属性,那么有什么方法可以保持纵横比并实现图像的理想尺寸?
最佳答案
是的,有一种方法可以保持图像的纵横比并将图像调整为原始大小的一小部分。但是,CSS 无法知道图像的固有尺寸(原始尺寸)。因此,您只能做两件事:
什么不起作用
使用百分比值作为
width
img
的值不能仅仅因为百分比值解析为它的 的百分比。容器尺寸 ,而不是它的原尺寸 .下面,我演示了不起作用的示例。话虽如此,我个人通常想明确指定图像的宽度。例如,在大型设备上,我希望图像为 1080 像素。在较小的设备上,我希望图像为 560 像素。我可以简单地为明确大小的图像创建一个容器,将图像放在容器内,并将图像的宽度指定为 100%(其容器大小)。
什么有效
如前所述,有两种方法可以使图像达到其原始宽度的 50%。首先,使用JS。其次,明确告诉 CSS 原始图像宽度。
intrinsicsize
attribute and set the width
and style
through CSS (仍然是实验性的,不支持)。如前所述,最后两个解决方案 大多数浏览器不支持,可能还不能正常工作。 在我看来,将图像的宽度设置为其固有宽度的 50% 的最佳选择是使用 JS。这是一个演示无效解决方案和 JS 解决方案的解决方案。如果您只更改图像的其中一个尺寸(宽度/高度),则会自动保持纵横比。
const imageJS = document.querySelector('.image--changed-with-js')
imageJS.onload = () => {
const intrinsicWidth = imageJS.width
imageJS.width = imageJS.width / 2
}
* {
box-sizing: border-box;
}
body,
html {
margin: 0px;
}
img {
margin: 20px 0;
}
/* Image has its intrinsic size (i.e. the original image size) */
.image--original {
width: auto;
}
/* Image contained within a 500px container
Image has a width of 50% of 500px = 250px */
.container {
width: 500px;
}
.image--changed-with-container {
width: 50%;
}
/* Image is not contained within a div
However, image is inside body
<body> is its container
It now has a width of 50% of the body
NOT 50% of its intrinsic width */
.image--changed-without-container {
width: 50%;
}
/* Image changed using JS
You can get the intrinsic size through JS and modify its size there */
.image--changed-with-js {}
<img class="image--original" src="https://img.freepik.com/free-vector/abstract-galaxy-background_1199-247.jpg?size=626&ext=jpg">
<div class="container">
<img class="image--changed-with-container" src="https://img.freepik.com/free-vector/abstract-galaxy-background_1199-247.jpg?size=626&ext=jpg">
</div>
<img class="image--changed-without-container" src="https://img.freepik.com/free-vector/abstract-galaxy-background_1199-247.jpg?size=626&ext=jpg">
<img class="image--changed-with-js" src="https://img.freepik.com/free-vector/abstract-galaxy-background_1199-247.jpg?size=626&ext=jpg">
关于javascript - 以 % 为单位缩放 HTML 图像的宽度和高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61585816/