将文本限制为同级图像的宽度/CSS 中的自动宽度 [英] Limit text to the width of sibling image / auto width in CSS
问题描述
我实际上是在尝试创建一个版本的figure"元素(即将在 HTML5 中推出),其中我有一张图片,下面有一个简短的描述.
但是,我想将整个元素的宽度限制为图像的宽度,因此文本不会比图像宽(必要时换行为多行).
基本 HTML:
<img src="..." alt="..." width="..." height="..."/><br/>图片说明
我精通 CSS,但我想不出任何纯 CSS 解决方案,而不将 style="width:100px"
添加到 div
以匹配图像宽度.
更新:经过一番搜索和思考,最好的方法似乎是在 div 上使用行内宽度.我将保留图像上的宽度属性,以防我希望 div 比图像宽一点(例如容纳更长的标题).
这种方法还意味着我可以并排放置两张图片,下方带有标题.如果我有一组相同大小的图像,我当然可以为每个 div
添加额外的样式.
感谢所有回答的人!
样式表
div.figure img,div.figure div.caption {宽度:100%;}div.figure div {溢出:隐藏;空白:nowrap;}
注意:要启用换行,只需删除最后一行 css
HTML
<img src="logo.png" alt="logo"/><div class="caption">图片的描述</div>
我已经在 Chrome、Firefox 和 IE7 中检查过它,并且在这三者中看起来都不错.我意识到这在 div 上有宽度而不是在 img 上,但至少你只需要在一个地方设置宽度.缺少使用 css 表达式(仅限 IE)我看不到将外部 div 宽度设置为第一个子元素宽度的方法.
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).
Basic HTML:
<div class="figure">
<img src="..." alt="..." width="..." height="..." /><br />
A description for the image
</div>
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.
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).
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
.
Thanks to everyone who answered!
Stylesheet
div.figure img,
div.figure div.caption {
width: 100%;
}
div.figure div {
overflow: hidden;
white-space: nowrap;
}
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>
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屋!