添加文本时,防止包含图像的div调整大小

时间:2011-03-09 12:37:12

标签: html css

我在网站中居中div并且包含图片。 div扩展了height以符合预期的图片。然后我添加了一些文字,我希望它在div的底部。但除此之外,div也会稍微调整一下,使其heighthigher,而不是图片的height。这是例子:

HTML:

<div class="siteContent">
    <img class="debug" src="../../Content/themes/base/images/pageTitle.png" /> 
    <span>
        aaa
    </span>
</div>

CSS:

body
{
    margin: 0;
}
.siteContent
{   
    width: 960px;
    margin-left: auto;
    margin-right: auto;
    border: thin solid;
}
.debug
{
    border: thin solid;
}

结果: enter image description here

不需要的效果标记为红色。

我能够通过像这样修改CSS来解决IE 8和Firefox的问题:

body
{
    margin: 0;
}
.siteContent
{   
    width: 960px;
    margin-left: auto;
    margin-right: auto;
    border: thin solid;
    position: relative;
}
.siteContent span{
    position: absolute;
    bottom: 0px;
}
.debug
{
    border: thin solid;
}

在runnig之后,我在Mozilla中得到了正确的结果:

enter image description here

然而,这对Chrome和Safary无效。 如何使其适用于所有主流浏览器?

3 个答案:

答案 0 :(得分:3)

这是因为图像与文本的基线对齐。尝试为您的图片设置vertical-align: bottomvertical-align: text-bottom来解决此问题。

答案 1 :(得分:2)

我认为这就是你想要的:http://jsfiddle.net/WEF49/3/ 在IE,Chrome和FF中测试过。这种方式img和span是底部对齐的,div没有任何额外的空间。不好的一面是div高度固定为img高度。如果你不介意div的固定高度,这是最干净的解决方案。

HTML:

<div class="siteContent">
    <img class="debug" src="http://t0.gstatic.com/images?q=tbn:ANd9GcRzjvZihxljFMlEt_IOypeOWYCgPgEvVrZ_DnwVTws5uR_iC_oFIg" /> 
    <span>
        aaa
    </span>
</div>

的CSS:

.siteContent
{   
    width: 960px;
    height: 213px;
    margin-left: auto;
    margin-right: auto;
    border: thin solid;
    overflow:hidden;
}
.debug
{
    border: thin solid;
}

答案 2 :(得分:1)

尝试添加overflow:hidden到没有高度的div +

<span style="clear:both">
        aaa
    </span>
+
<img src="..." style="clear:both" />

将style =“*”带到你的css文件(ofcource)

相关问题