图像标题宽度与图像相同

问题描述 投票:0回答:7

如何使图像标题宽度与图像相同?现在我有以下代码:

<div class="image">
    <img src="foo.jpg" alt="" />
    <div>This is the caption.</div>
</div>

我已经尝试了很多东西(浮动、绝对定位等),但如果标题很长,它总是使 div 变宽而不是多行。问题是我不知道图像的宽度(或标题的长度)。解决这个问题的唯一方法是使用表吗?

html css image width caption
7个回答
41
投票

所以问题是你不知道img会有多宽,而img的标题可能会超出img的宽度,在这种情况下你想将标题的宽度限制为img的宽度.

在我的例子中,我在父元素上应用了

display:table
,并在标题元素上应用了
display:table-caption
caption-side:bottom
,如下所示:

<div class="image" style="display:table;">
    <img src="foo.jpg" alt="" />
    <div style="display:table-caption;caption-side:bottom;">This is the caption.</div>
</div>

6
投票

您可以应用

display:table;
和任意初始宽度,例如。
width:7px;
到父块,如
figure
,一切都会按预期工作!

这是一个现场演示: http://jsfiddle.net/blaker/8snwd/

此解决方案的限制是 IE 7 及更早版本不支持

display:table;
,而 IE 8 要求您的文档类型为
!DOCTYPE

来源:


2
投票

如果问题是标题太长,您可以随时使用


div.image {
    width: 200px; /* the width you want */
    max-width: 200px; /* same as above */ 
}
div.image div {
    width: 100%;
}

并且标题将保持静态。另外,标签名称是img,而不是image。

或者,如果你想检测图像宽度,你可以使用 jQuery:


$(document).ready(function() {
    var imgWidth = $('.image img').width();
    $('.image div').css({width: imgWidth});
});

这样,您就可以获得图像宽度,然后将标题宽度设置为它。


1
投票

正确添加字幕的唯一方法是将图像和标题包含在由具有 table、table-row 和 table-cell css 属性的 span 元素构造的表格中。

任何其他方法(包括 HTML5 图形标签)都会导致宽度不匹配或导致不必要的换行。

如果您的方法必须在非 CSS3 浏览器中工作,那么表格可能是最好的选择。


0
投票

扩展上述内容,我使用此 jQuery 代码片段来检查代码中具有标题的所有图像,并将标题宽度设置为与前一个图像的宽度相匹配。所以如果 HTML 是这样的:

<img src="blah" /><figcaption>this is the first caption</figcaption>
<img src="blah2" /><figcaption>this is the second caption</figcaption>

然后使用这个 jQuery:

$("figcaption").each(function () { 
    $(this).css("width", $(this).prev("img").width()) 
});

-1
投票

您可以尝试设置图像div包装器

display:inline-block

http://jsfiddle.net/steweb/98Xvr/

如果标题很长,唯一的解决办法就是设置固定宽度,或者通过js设置.image div宽度。我正在尝试考虑一个纯 css 解决方案,但我认为这是一个艰巨的挑战:)


-1
投票

关键是将图像视为具有一定的宽度和一定的长度。在下面的示例中,我检查了图像的宽度为 200 像素。然后将标题视为内联块。

HTML:

<div style="width:200px;">
   <img src="anImage.png" alt="Image description"/>
   <div class="caption">This can be as long as you want.</div>
</div>

CSS:

.caption {
   display: inline-block;
}

您还可以通过将上面的 css 替换为以下内容之一,将内联块替换为左对齐、右对齐或拉伸到精确图像宽度的文本:

.caption {
   /* text-align: left; */
   /* text-align: right; */
   text-align: justify;
}
© www.soinside.com 2019 - 2024. All rights reserved.