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:
<nav>
<a href="#">Home</a>
<a href="#">About</a>
<a href="#">Contact</a>
</nav>
With the following CSS:
nav { background: #555; }
nav a {
display: inline-block;
padding: 1rem;
text-transform: uppercase;
color: #fff;
text-decoration: none;
}
By default, the navigation bar will look something like this:
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
:
nav { background: #555; width: fit-content; }
Now we gain the ability to center-align the navigation bar, despite never setting an explicit width on it:
nav { margin: 0 auto; }
The result:
This can also work for images and other replaced elements:
figure {
border: 2px solid #222;
width: fit-content;
background: #555;
font-size: 0;
}
figure img {
width: 200px;
}