Nem*_*eme 2 html css responsive-images
为了使响应图像在小屏幕上按比例缩小,我目前使用max-width: 100%;(或固定的最大宽度).与指定固定大小相反,这有一个可怕的缩小,因为当页面加载时,浏览器不为图像分配空间,只能在开始下载后才这样做.在加载所有图像之前,这会导致大量布局重排和糟糕的体验.
这似乎很容易修复 - 毕竟,我只需告诉浏览器实际大小是什么,以便它可以在下载前找出宽高比和最终大小.首先,我想知道这是什么width和heighthtml属性是什么,但我知道这不是他们的目的,因为他们可以用于重新缩放图像和更改最终大小.
我真正想要的是像" srcwidth"和" srcheight"那样告诉浏览器图像文件的实际大小,以便在知道宽高比以使用max-width样式之前不必加载.但是根据我的发现,没有像这些属性这样的东西.真的没有办法实现这个目标吗?
我尝试以这种方式使用实际width和heighthtml属性,然后用CSS覆盖它,但浏览器根本不关心它.
我看到这个问题最常见的方法是将所有图像放在容器中,然后使用padding-bottom属性"预先分配"高度.
<div class="responsive-container">
<img src="image.jpg"/>
</div>
Run Code Online (Sandbox Code Playgroud)
为此,您需要知道图像的纵横比以计算填充.
使用纵横比计算出高度
例如,对于16:9(例如800 x 450px)的纵横比,高度是宽度的56.25%,因此这将是填充的值.
.responsive-container {
width: 100%;
padding-bottom: 56.25%; /* 9/16 = aspect ratio of image */
position: relative;
height: 0;
overflow: hidden;
}
.responsive-container img {
position: absolute;
top: 0;
left: 0;
width: 100%;
}
Run Code Online (Sandbox Code Playgroud)
不同的方面比率
如果您的图像具有不同的宽高比,但您仍然可以提前知道,则为每个图像设置不同的类,例如
.responsive-container {
width: 100%;
position: relative;
height: 0;
overflow: hidden;
}
.ratio-16-9{
padding-bottom:56.25%; /* 9/16*100 */
}
.ratio-4-3{
padding-bottom:75%; /* 3/4*100 */
}
.ratio-1-1{
padding-bottom:100%;
}
Run Code Online (Sandbox Code Playgroud)
并在html中使用它:
<div class="responsive-container ratio-16-9">
<img src="image.jpg"/>
</div>
Run Code Online (Sandbox Code Playgroud)
动态计算高度
最后,如果您希望CSS为每个图像动态计算高度,您可以使用CSS calc()来计算高度,如下所示:
calc((image_height/image_width)*100%)
Run Code Online (Sandbox Code Playgroud)
所以你的CSS将是:.responsive-container {width:100%; 位置:相对; 身高:0; 溢出:隐藏; }
你这样使用它:
<div class="responsive-container" style="padding-bottom: calc((426/640)*100%);" >
<img src="image.jpg"/>
</div>
Run Code Online (Sandbox Code Playgroud)
参考
| 归档时间: |
|
| 查看次数: |
1057 次 |
| 最近记录: |