skip navigation

Min, Max, and Fit Content

random image
This is a random image that is 400px wide. The parent figure element has its width set to min-content so this text will never be wider than the widest word or element which is the image above.

The default width setting for block level elements is auto, not 100%. What’s the difference? Well auto takes up the available space whereas 100% is the width of the space. If something is added like a left or right margin its width is added to the 100% making it overflow it’s container.

So what about setting the width to max-content, min-content or fit-content?

The headings below show the differences. You can edit the text of these examples to make it longer. Just click inside the elements somewhere and type.

Using a standard h2

The problem here is that you might not always want the background to extend beyond the width of the text.

Using min-content

The block level element will only go to the minimum width it needs to be. That is the length of the longest word or the width of an image if it has a fixed width.

This can be useful when you have an image with text underneath that you want to stay the same width as the image as above.

Using max-content

Looks the same as fit-content but with longer lines it’s a bit like <pre> in that it will just keep on going, overflowing container elements. The text of this is editable to trying adding more to see what happesn.

Using fit-content

The fit-content property works similarly to setting a block level element to inline-block. Like max-content it will only extend as long as it needs to be. But unlike max-content it won’t overflow elements and will wrap the text when it reaches the limit of it’s parent element.

Again try editing the text to see what happens with longer line lengths.