html - CSS - 让文本使用兄弟 block 元素的最大宽度

标签 html css

我目前正在解决这个问题,我正在尝试向图像元素添加标题。如果标题的宽度大于图像,则标题应换行。

<figure class="caption">
    <a href="#" target="_blank">
        <img src="/sample_image" alt="">
    </a>
    <figcaption>This is a sample-caption that should wrap if it's width exceeds the width of the image</figcaption>
</figure>

正常情况下,像这样的一些 CSS 代码应该可以完成工作:

figure {
    display: table;
    width: 50px;
}
figcaption {
    display: table-row;
}

问题是,这不能与以下用于为移动设备自动缩放图像的 CSS 结合使用:

img {
    max-width: 100%;
}

所以这里提到的解决方案https://stackoverflow.com/a/617455/583569不会工作。 我知道,这不是一个好的解决方案,但目前将所有图像转换为各种格式需要很长时间。

是否有可能的非 JS 解决方案来解决此问题?

最佳答案

我认为这可能适合您,但此解决方案有局限性。

如果这是您的 HTML:

<figure class="caption">
    <a href="#" target="_blank">
        <img src="http://placehold.it/300x200" alt="">
    </a>
    <figcaption>This is a sample-caption that should wrap 
                if it's width exceeds the width of the image</figcaption>
</figure>

并应用CSS:

figure {
    display: inline-block;
    position: relative;
    border: 1px dotted gray;
}
figure a {
    display: inline-block;
}
figure img {
    vertical-align: top;
    width: 100%;
    margin-bottom: 70px;
}

figure figcaption {
    position: absolute;
    bottom: 0;
    left: 0;
    width: inherit;
    height: 70px;
}

参见 fiddle 演示:http://jsfiddle.net/audetwebdesign/H3Ngz/

评论

主要问题是我们需要允许 figure 的宽度缩小以适合图像,使用 inline-block 并不难做到缩小以适合其内容的元素。

但是,需要用图像包裹 figcaption 以限制宽度。 如果您通过设置 width: inherit 使用绝对定位,就可以做到这一点。

这就引出了另外一个问题,figcaption的高度怎么办?

如果标题下方没有内容,只需让它向下展开即可 不与任何其他内容重叠。

但是,由于绝对定位,标题文本不在内容流中,因此当视口(viewport)更改宽度时文本回流时,有办法允许其高度。

一个有限但可能的解决方法是为 figcaption 指定高度或允许在标题中使用滚动条。

问题是你不知道字幕文本的长度...

一点点 jQuery 就能修复这些限制的日志。

关于html - CSS - 让文本使用兄弟 block 元素的最大宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18465799/

相关文章:

html - HTML 网站上使用的 Wordpress 革命 slider

CSS3 第一个 div 唯一技巧

html - 标题元素中文本周围的空间

html - Bootstrap Div 或 Span 类似 form-group input-group-addon

html - 什么是规范网址?

当突出显示和插入时,JavaScript 不允许将点作为第一个

javascript - 在页面上将所有 glyphicon-chevron 的方向更改为向上或向下

html - 为什么我的 HTML 标记会删除它前面的空格,为什么这里的换行符不起作用?

javascript - 如何通过 JQuery 删除 div 上应用的 css?

javascript - 数据表中的图标意外显示