In previous articles I’ve explored some of the new intrinsic and extrinsic CSS values such as object-fit, max-content and min-content . While still officially labeled “experimental”, these values have excellent browser support when provided with appropriate vendor prefixes.
Existing somewhere between max-content and min-content, fit-content can be very helpful, particularly when creating responsive designs.
Shrink-Wrapping Without Snapping
min-content is excellent for aligning groups of content with unknown width, such as a site navigation bar:
Rather than taking the entire width of its parent, what if we want to collapse the bar down to its smallest possible width, without breaking any of the links onto a new line? We can achieve that with fit-content:
The result, after setting two images inside the <figure> element:
Note that the width of the images must be defined in order for fit-content to work. However, designers must be careful when using percentages; if the content widths do not add up, the leftover space will be retained:
Obviously, the container also assumes a width of 100% of its parent in this case.
Prefixes & Fallbacks
fit-content currently requires vendor prefixes to gain full support. Like a few other exceptions in CSS, the prefix goes in front of the value, not the property:
fit-content is not yet supported in Internet Explorer or Opera Mini, but excellent fallbacks use the display property: specifically, display: inline-block or display: table, both of which exhibit very similar behavior to width: fit-content.
The one downside of using display: inline-block is that it will force you to confront the value’s known problems with whitespace, but both it and displaying the element with table CSS work well. For complete coverage, you’ll want to use both: