CSS - fit-content Property



The fit-content property in CSS is used to specify the size of a container based on its content, up to a maximum size. It is commonly used in combination with the min-content and max-content values to create flexible and responsive layouts.

  • In practice, this means that the frame utilizes the available space, ensuring that it never exceeds the size of max-content.

  • When used with specified dimensions for width, height, min-width, min-height, max-width and max-height in a layout box, the minimum and maximum sizes refer to the dimensions of the content.

This property is particularly useful in situations where you want a container to expand or shrink based on its content but still have an upper limit to prevent it from becoming too wide.

Syntax

width: fit-content;
block-size: fit-content; 

CSS fit-content() - Box Sizing

Following

  • In the example given, the fit-content function for the width property of the box class dynamically adjusts the width of the box to the content.

  • It ensures that the box adapts to the content, allowing the box to grow or shrink while maintaining a minimum width necessary to contain the content.

<html>
<head>
<style>
   body {
      justify-content: center;
      align-items: center;
      height: 100vh;
      margin: 0;
   }

   .box {
      width: fit-content;
      padding: 20px;
      background-color: #3498db;
      border:2px solid black;
      color: white;
      font-size: 18px;
      margin-bottom:5px;
   }
</style>
</head>
<body>
   <div class="box">
      Small content!
   </div>
   <div class="box">
      Some more content shows how the box expands!
   </div>
   <div class="box">
     Lot of content shows how the box expands even more !Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>
</body>
</html>    
Advertisements