To make a container element shrink-to-fit around an inner element (such as an image) you can use for example CSS display: inline-block
, position: absolute
or float
. But without an explicit container width, any text content above or below the inner element will expand the container instead of wrapping into multiple lines.
Here's a CSS hack using display: inline-table
that only requires a 1px default width for the container, so that you don't need to measure the exact width of the inner element. This might be useful in image galleries where image dimensions vary in size.
Tested to work in:
The container element is styled as a CSS table with display: inline-table
. Since tables expand to fit their content regardless of the specified width, you can simply give the container a 1px default width value. If the inner element is wider than that it will expand the table (which is technically the opposite of shrinking to fit), while long lines of text will still wrap into multiple lines.
If the inner element is an IMG element you might instead let a server-side script find the image file's width, and then use that value when generating the markup. A disadvantage is that this probably requires inline styling of the container element, something which is usually best avoided. Here's a basic example using PHP's getImageSize() function:
<?php
function create_image_container($src)
{
$size=getImageSize($src);
echo '<div style="width: '.$size[0].'px;">
<img src="'.$src.'" alt="">
</div>';
}
?>
published: May 15, 2016
last modified: Jan 26, 2017