CSS - HTML:内联框扩展大于预期?

时间:2012-08-16 13:30:01

标签: html css html5 css3

我正在创建我的第一个博客模板。

我希望像维基百科这样的内嵌图像旁边有文章的段落。我用以下代码实现了这个目标:

<div class="photo">
    <img src="image_file.jpg">
</div>
div[class='photo'] {
    margin: 10px;
    float: left;
    clear: left;
}
img {
    max-width: 500px;
    min-width: 150px;
    margin: 8px;
}

到目前为止一切正常。但是,我还想在图像文件下面加上一个标题,所以我在

后面引入一个

标题

<div class="photo">
    <img src="image_file.jpg">
    <p>Caption for the image file which might be long</p>
</div>

不幸的是,这个<p>使得这张照片div扩展得比照片本身更大,使它看起来很有趣。我希望max-width与照片一样大,如果文字很大,我会去第2或第3行。

我怎样才能做到这一点?我尝试了width: auto; display: block;,将<p>放在另一个div中,但它失败了。

感谢您的帮助。

PS。我知道我可以通过JS加载页面后解决问题,但我很想学习以正确的CSS方式解决它。谢谢!

2 个答案:

答案 0 :(得分:1)

试试这个 - DEMO

<强> HTML

<div class="photo">
    <img src="image_file.jpg">
    <p>Caption for the image file which might be long</p>
</div>

<强> CSS

div.photo {
    margin: 10px;
    float: left;
    clear: left;
    position: relative;
    background: honeydew;
}

div.photo img {
    max-width: 500px;
    min-width: 150px;
    margin: 8px;
}


div.photo p {
    position: absolute;
    bottom: 12px;
    left: 10px;
    right: 8px;
    background: rgba(0, 0, 0, .4);
    color: #fff;
}

答案 1 :(得分:1)

如果问题只是div宽度大于img宽度,您可以尝试将p移出#photo并将其放入另一个div <div class="photoBox"> <div class="photo"> <img src="image_file.jpg"> </div> <p>Caption for the image file which might be long</p> </div> 1}}:

div.photoBox {
    margin: 10px;
    float: left;
    clear: left;
}
img {
    max-width: 500px;
    min-width: 150px;
    margin: 8px;
}

...然后相应地更改CSS:

{{1}}