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

TK1*_*123 2 html css

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

https://jsfiddle.net/strz3stt/

注意:我正在尝试使用现有的标记,因此我需要一种方法来使用CSS,因为我无法编辑标记.

HTML:

<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>
Run Code Online (Sandbox Code Playgroud)

CSS:

.wrapper {
  border: 3px solid red;
  display: inline-block;
}
.wrapper img {
  border: 1px solid blue;
}
.wrapper a {
  display: block;
  border: 1px solid green;
}
Run Code Online (Sandbox Code Playgroud)

Mr *_*ter 5

假设您打算将链接的文本包装到图像的宽度,您可以做的是将包装器转换为表格.然后,您可以通过设置强制宽度为其内容的宽度width: 1px.
(这也将巧妙地处理文本中的单词恰好比图像宽的情况.)

.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;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

此外,您应该考虑使用<figure>而不是<span>包装器.这正是<figure>为了什么.