如何使div包含和image元素具有与图像相同的高度

时间:2013-03-29 17:17:03

标签: css

我有这个HTML代码:

<div>
    <img src="http://placehold.it/319x300" alt="">
<div>

和这个css:

*{margin: 0; padding: 0;}
div{
    background: red;
    width: 319px;
    height: auto;
}
img{
    width: 100%;
    height: auto;
}

然而,div的背景颜色显示在底部。有没有办法让容器与图像的高度相同?在我正在处理的网站上,我有Erics重置样式,并且没有paddingmargin与此冲突。这是示例代码http://jsfiddle.net/ESmZW/1/ 感谢

4 个答案:

答案 0 :(得分:2)

快速方法是将vertical-align:top属性添加到图像

img{
    width: 100%;
    height: auto;
    vertical-align:top;
}

<强> jsFiddle example

你也可以向左浮动图像并将溢出:自动规则添加到div中,就像在 jsFiddle example 中一样。

答案 1 :(得分:0)

在图像上设置“display:block”。

img {
    width: 100%;
    height: auto;
    display: block;
}

答案 2 :(得分:0)

您可以使用绝对/相对定位:

*{margin: 0; padding: 0;}
div{
    position:relative;
    background: red;
    width: 319px;
    height: auto;
}
img{
    position:absolute;
    width: 100%;
    height: auto;
}

答案 3 :(得分:0)

@aurel如果您想要的是将div设置为图像的大小,为什么不将它的高度和宽度设置为图像的大小?您的HTML也不会关闭您的div。在jsfiddle上查看我的修改。

<div>
    <img src="http://placehold.it/319x300" width="319" height="300" alt="">
</div>

body {
    margin:0;
}


div {
    background: red;
    width: 319px;
    height: 300px;
}