我希望我的图像的宽度自动调整大小(使用图像纵横比)。我使用类似的东西:
img {
height: 100%;
width: auto;
}
问题是在加载图像之前,浏览器不会为其预留水平空间。有没有办法让浏览器在不使用 javascript 的情况下为我的图像保留空间?
我知道图片的纵横比以及全尺寸图片的高度和宽度。
最佳答案
实际上,只要您至少知道图像的纵横比,就有办法做到这一点。
我成功使用的技术涉及根据图像的比例向图像周围的包装器添加填充。此技术由 Thierry Koblentz 引入(用于视频)并由 Anders M. Andersen 扩展(用于图像)。
<div class="grumpy-image-wrapper">
<img class="grumpy-image" src="images/grumpy-cat.jpg" />
</div>
<div class="grumpy-image-wrapper">
<img class="grumpy-image" src="images/grumpy-cat.jpg" />
</div>
<div class="grumpy-image-wrapper">
<img class="grumpy-image" src="images/grumpy-cat.jpg" />
</div>
.grumpy-image-wrapper {
width: 90%;
height: 0;
padding-bottom: 66.67%; /* determined by image aspect ratio */
border: 2px solid white;
position: relative;
}
.grumpy-image {
width: 100%;
position: absolute;
}
在这里阅读更多:https://www.andyshora.com/css-image-container-padding-hack.html
关于html - 为自动调整大小的 img 保留空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16735988/