Languages
[Edit]
EN

CSS - sizing elements using min-content, max-content and fit-content

0 points
Created by:
Marley-Marks
712

In this article, we would like to show you how to set the size of the elements using min-content, max-content and fit-content.

Quick solution:

// ONLINE-RUNNER:browser;

<style> div { border: 2px dashed #28a745; margin-top: 10px; } </style>

<div style="width: min-content;">min-content</div>
<div style="width: max-content;">max-content</div>
<div style="width: fit-content;">fit-content</div>
<div style="width: auto;">auto</div>

Warning: The min-content and max-content were introduced to some major browsers around 2015-2020.

 

Practical example

In this example, we create four classes to compare the different sizes of elements:

  • auto - default layout which is full container size,
  • min-content - as small as possible to fit all the content, which is usually the largest piece of text,
  • max-content - as wide as possible to fit all the content (never shrinks down),
  • fit-content -  as wide as possible to fit all the content but shrinks down until becomes the same size as min-content, then it stops shrinking. In short: max-content at full size, min-content at minimum size, otherwise fills the full container.
// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <style>
    
    div { border: 2px dashed #28a745; margin: 10px; }
    
    .min { width: min-content; }
    
    .max { width: max-content; }
    
    .fit { width: fit-content; }
    
    .auto { width: auto; }
    
  </style>
</head>
<body>
  <div class="min">min-content</div>
  <div class="max">max-content</div>
  <div class="fit">fit-content</div>
  <div class="auto">auto</div>
</body>
</html>

 

References

  1. fit-content - CSS: Cascading Style Sheets | MDN
  2. min-content - CSS: Cascading Style Sheets | MDN
  3. max-content - CSS: Cascading Style Sheets | MDN

Alternative titles

  1. CSS - set element size using min-content, max-content and fit-content
  2. CSS - min-content, max-content, fit-content and auto comparison
  3. CSS - difference between min-content, max-content, fit-content and auto
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join