TK123 TK123 - 1 month ago 4
HTML Question

CSS: wrap container element around image and not text even if image is smaller?

I would like the red container element to be the width of the image not the text, but it spans to the size of the text because it's wider. How to achieve this?

https://jsfiddle.net/strz3stt/

Note: I'm trying to work with existent markup so I need a way to do this with CSS only as I can't edit the markup.

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;
}

Answer

Assuming it's your intention to wrap the text of the link to the width of the image, what you can do is turn the wrapper into a table. Then you can force the width to be the width of its contents, by setting width: 1px.
(This will also neatly handle the case where a word in the text happens to be wider than the image.)

.wrapper {
  border: 3px solid red;
  display: table; width: 1px;
}
.wrapper img {
  border: 1px solid blue;
}
.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>

Also, you should consider using a <figure> rather than a <span> for the wrapper. This is precisely what <figure> is for.

Comments