将 div 宽度限制为其内部流体图像的宽度
晚上前端向导。我正在尝试做一些应该非常简单的事情:我想让图像在我的正文内容中向右或向左浮动,并在每个图像下方都有一个标题。为了尝试实现这一目标,我浮动了一个 div,其中包含图像,然后是一个带有下面标题的跨度。我已将图像最大宽度设置为 100%,因此我的布局具有响应能力。
有没有什么方法只使用 CSS 和 HTML 就可以将包含的 div 的宽度限制为其内部图像的宽度?我发现下面的跨度超出了 div 的宽度,无论它是否为 display:inline-block 。我希望跨度始终与图像的宽度相同,以便文本与图像的右边缘对齐。
我希望能够使用不同宽度的图像,因此在 div 上设置最大宽度并不能真正解决问题。我可以用 JQuery 轻松地做到这一点,但那是作弊。
如有任何建议,不胜感激!你可以在 http://jsfiddle.net/andfinally/yBHjK/ 看到我在说什么
Evening front end wizards. I'm trying to do something that should be quite simple: I want to have images floated right or left in my body content, with a caption below each image. To try and achieve this I'm floating a div with the image inside it, followed by a span with a caption below. I've given the image max-width 100% so my layout is responsive.
Is there any way using just CSS and HTML that I can constrain the width of the containing div to the width of the image inside it? I'm finding that the span below pushes out the width of the div, whether it's display:inline-block or not. I'd like the span to always be the same width as the image, so the text wraps in line with the image's right edge.
I'd like to be able to use images of varying widths, so setting a max-width on the div doesn't really do the trick. I could do it easily enough with JQuery, but that would be cheating.
Any suggestions gratefully received! You can see what I'm talking about at http://jsfiddle.net/andfinally/yBHjK/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试为容器设置
max-width
,然后为图像设置width: 100%
。它应该有效。看看http://jsfiddle.net/nMEVd/1/
Try setting a
max-width
to the container and thenwidth: 100%
to the image. It should work.Look http://jsfiddle.net/nMEVd/1/
听起来您希望包含的 div 仅针对 img 元素而不是 span 元素扩展其宽度。这是正确的吗?
对此没有纯 CSS 解决方案,JavaScript 是实现您所追求的目标的最佳方法。
两个类似的问题:
CSS:强制文本换行(或仅通过其子元素之一定义元素宽度)
将文本限制为同级图像/自动的宽度CSS 中的宽度
It sounds like you want the containing div to expand it's width only for img elements and not span elements. Is that correct?
There is no pure CSS solution for this, JavaScript is the best way to achieve what you're after.
Two similar questions:
CSS: Force text to wrap (OR defining element width by only one of its children)
Limit text to the width of sibling image / auto width in CSS
您可能想尝试添加:
到span元素,或者在CSS表中添加:
编辑:
这应该会打破 span 元素中的文本以适应两行或多行,而不是超出图像的宽度。
You might want to try adding:
to the span elememt, or in a css sheet with:
Edit:
This should break the text in your span element to fit across two or more lines instead of stretching out past your image's width.