如何设置宽(100%)宽和未知高度的图片,使其不会弹出 [英] How do I style an image with full (100%) width and unknown height so it doesn't pop

查看:103
本文介绍了如何设置宽(100%)宽和未知高度的图片,使其不会弹出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在建立一个网站,其中大多数的图像是全流血的,也就是说,它们的宽度:100%。我有一个问题,其中图像的高度为0,直到加载,这导致网站的元素跳了很多。

I'm building a site where most of the images go full-bleed, that is, they are width:100%. I am having a problem where the images have a height of 0 until loaded which causes the elements of site to jump around a lot.


  • 我无法将其留空,因为在载入后为0。

  • 设置高度为一个像素值,它不能正确缩放。

  • 我不能真正将其设置为100%,因为它使用
    包含元素的高度。

我想做的是什么?我可以想办法在第一个图片加载后使用javascript可能解决这个问题,但似乎不是很优雅。

Is what I'm trying to do possible? I can think of ways to possibly solve this using javascript after the first image loads, but doesn't seem very elegant.

帮助!

<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%; }

JSFiddle

推荐答案

你最好做的是有一个包装 div <

The best you could do is have a wrapper div element which is fluid in the sense that it matches image's aspect ratio.

像下面这样:

HTML

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%;
}

小提琴: http://jsfiddle.net/Varinder/m8dFM/1/

这篇关于如何设置宽(100%)宽和未知高度的图片,使其不会弹出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆