首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >CSS:将容器元素封装在图像周围,而不是文本,即使图像较小?

CSS:将容器元素封装在图像周围,而不是文本,即使图像较小?
EN

Stack Overflow用户
提问于 2016-10-25 16:29:10
回答 1查看 113关注 0票数 2

我希望红色容器元素是图像的宽度,而不是文本,但它跨越文本的大小,因为它更宽。如何做到这一点?

https://jsfiddle.net/strz3stt/

注意:我试图使用现有的标记,所以我需要一种方法来处理CSS,因为我不能编辑标记。

HTML:

代码语言:javascript
复制
<span class="wrapper">
  <img src="https://placekitten.com/g/400/300">
  <a href="http://google.com">Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google </a>
</span>

CSS:

代码语言:javascript
复制
.wrapper {
  border: 3px solid red;
  display: inline-block;
}
.wrapper img {
  border: 1px solid blue;
}
.wrapper a {
  display: block;
  border: 1px solid green;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-10-25 16:57:01

假设您打算将链接的文本包装到图像的宽度,那么您可以做的就是将包装器转换成一个表。然后,通过设置width: 1px,可以将宽度强制为其内容的宽度。

(这还可以很好地处理文本中的单词恰好比图像更宽的情况。)

代码语言:javascript
复制
.wrapper {
  border: 3px solid red;
  display: table; width: 1px;
}
.wrapper img {
  border: 1px solid blue;
  max-width: calc(100vw - 22px);
}
.wrapper a {
  display: block;
  border: 1px solid green;
}
代码语言:javascript
复制
<span class="wrapper">
  <img src="https://placekitten.com/g/400/300">
  <a href="http://google.com">Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google </a>
</span>

另外,您应该考虑使用<figure>而不是<span>作为包装器。这正是<figure>的作用所在。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40245147

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档