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

时间:2016-10-25 16:29:11

标签: 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>

CSS:

.wrapper {
  border: 3px solid red;
  display: inline-block;
}
.wrapper img {
  border: 1px solid blue;
}
.wrapper a {
  display: block;
  border: 1px solid green;
}

1 个答案:

答案 0 :(得分: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;
}
<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>的用途。