css - 具有百分比宽度值的 DIV 图像包装高度错误

标签 css html image

我想将图像包装到 html DIV 中,因为我希望它可以随窗口大小完全缩放,所以我想设置 DIV< 的宽度 百分比如下:

html

<div id="wrapper">
    <img src="http://openclipart.org/people/netalloy/rally-car.svg" />
</div>

CSS

#wrapper {
    position: absolute;
    width: 50%;
}

#wrapper img {
    width: 100%;
}

图像应决定其容器的高度。这是因为图像宽度设置为 100%,并且图像高度是根据正确的宽高比计算的。

结果在 jsfiddle 上可见:http://jsfiddle.net/lorenzopolidori/5BN4g/15/

我的问题是:

  1. 为什么所有现代浏览器都将包装器 DIV 渲染为比内部图像高 5px?
  2. 如何消除这个 5 像素的差距,同时仍然以百分比设置所有尺寸并且使用 javascript?

令人惊讶的是,这种情况发生在 Chrome (21.0.1180.89)、Firefox (15.0.1) 和 IE8 中,而 IE7 正确呈现它,使 DIV 的高度与图像的高度匹配。

最佳答案

检查一下:

http://jsfiddle.net/5BN4g/29/

这是一个行高问题:-)

你需要:

#wrapper {
    width: 60%;
    background-color: #aaa;
    margin: 50px auto;
    line-height:0;
}

#wrapper img {
    width:100%;
    border: 1px dashed red;
    box-sizing:border-box;
}
​

我使用 box-sizing 来确保图像的宽度不会溢出容器

关于css - 具有百分比宽度值的 DIV 图像包装高度错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12581403/

相关文章:

javascript - 在 HTML TABLE 中的每一行之后切换

javascript - jQuery .load 返回空 div(PHP 页面)

java - 将图像添加到 JFrame 时出现问题

ruby-on-rails - rails 3 : Image streaming error: “The image … cannot be displayed because it contains errors”

css - getComputedStyle 返回 CSSStyleDeclaration 但访问时所有属性均为空

jquery - 使用 jQuery 在单独的 DIV 中包装任意内容(H2、H3、P 等)

html - 将选定的列表项向右移动并溢出

图像加载前的 CSS 图像布局

javascript - CSS 变量未在 Mobile Safari 上更新

jquery - 当浏览器滚动到某个元素时更改该元素的 CSS