我正在构建一个网站,其中大部分图像都全出血,也就是说,它们的宽度为:100%。我遇到一个问题,图像在加载之前的高度为 0,这会导致网站元素跳来跳去。
- 我不能将它留空,因为在加载之前它是 0。
- 如果我将高度设置为像素值,它无法正确缩放。
- 我真的不能将它设置为 100%,因为它使用了 包含元素。
我想做的事情可行吗?我可以想办法在第一个图像加载后使用 javascript 解决这个问题,但看起来不是很优雅。
帮助!
<img src="http://lorempixel.com/1280/640/cats/1" id="auto" />
<p>This text will get pushed down after load starts</p>
<img src="http://lorempixel.com/1280/640/cats/2" id="fixed" />
<p>This text will get pushed down after load starts</p>
<img src="http://lorempixel.com/1280/640/cats/3" id="percentage" />
<p>This text will get pushed down after load starts</p>
img { width:100%; }
#auto { height: auto; }
#fixed { height: 640px; }
#percentage { height: 100%; }
最佳答案
你能做的最好的事情是有一个包装器 div
元素,它是流动的,因为它与图像的宽高比相匹配。
如下所示:
HTML
<div class="image-wrapper">
<img src="http://lorempixel.com/1280/640/cats/1" />
</div>
<p>This text will get pushed down after load starts</p>
<div class="image-wrapper">
<img src="http://lorempixel.com/1280/640/cats/2" />
</div>
<p>This text will get pushed down after load starts</p>
<div class="image-wrapper">
<img src="http://lorempixel.com/1280/640/cats/3" />
</div>
<p>This text will get pushed down after load starts</p>
CSS
.image-wrapper {
position:relative;
height:0;
padding-bottom:50%; /* aspect ratio of the image ( ( 640 / 1280 ) * 100% ; ) */
}
.image-wrapper > img {
position:absolute;
top:0;
left:0;
width:100%;
}
关于javascript - 如何设置全宽 (100%) 和未知高度的图像样式,使其不会弹出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21446761/