将文本限制为CSS中的兄弟图像宽度/自动宽度 [英] Limit text to the width of sibling image / auto width in CSS

查看:206
本文介绍了将文本限制为CSS中的兄弟图像宽度/自动宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我基本上试图创建一个版本的figure元素(即将到来的HTML5),其中我有一个简短的描述下面的图片。

I am essentially trying to create a version of the "figure" element (upcoming in HTML5), whereby I have an image with a short description below it.

但是,我想将整个元素的宽度限制为图片的宽度,因此文本不会宽于图片(如有必要可以换行到多行)。

However, I want to limit the width of this entire element to that of the image, so the text isn't wider than the image (wrapping to multiple lines if necessary).

基本HTML:

<div class="figure">
<img src="..." alt="..." width="..." height="..." /><br />
A description for the image
</div>

我熟悉CSS,但我不能想到任何纯CSS解决方案,在 div 中添加 style =width:100px以匹配图片宽度。

I'm well-versed with CSS but I can't think of any pure CSS solution, without adding a style="width:100px" to the div to match the image width.

更新:经过一番搜索和思考,最好的方法似乎是在div上使用内联宽度。我会保留图片上的宽度属性,以防万一我们希望div比图片宽一些(例如,为了容纳更长的字幕)。

Update: After a bit of searching and thinking, the best method seems to be using an inline width on the div. I will keep the width attribute on the image, in case I wish the div to be a bit wider than the image (for example to accomodate a longer caption).

方法也意味着我可以有两个图像并排,并在下面有一个标题。如果我有一组相同大小的图片,我当然可以为每个 div 添加额外的样式。

This approach also means I could have two images side-by-side with a caption below. If I have a set of images the same size, I can of course add an extra style to each div.

感谢所有回答的人。

推荐答案

样式表

div.figure img,
div.figure div.caption {
    width: 100%;
}
div.figure div {
    overflow: hidden;
    white-space: nowrap;
}

注意:启用包装只是删除最后一个css行

note: to enable wrapping just remove that last css line

HTML

<div class="figure" style="width:150px;">
    <img src="logo.png" alt="logo" />
    <div class="caption">A description for the image</div>
</div>

我已经在Chrome,Firefox和IE7中检查过,它看起来不错。我意识到这有宽度在div而不是img,但至少你只需要在一个地方设置宽度。缺少使用css表达式(仅IE)我看不到一个方法设置外div的宽度为第一个子元素的宽度。

I've checked it in Chrome, Firefox and IE7 and it looks good in all three. I realise this has the width on the div and not the img, but at least you only need to set the width in one place. Short of using css-expressions (IE only) I can't see a way of setting the outer divs width to the width of the first child element.

这篇关于将文本限制为CSS中的兄弟图像宽度/自动宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆