CSS - fit-content 属性



CSS 中的fit-content属性用于根据内容指定容器的大小,但大小不超过最大值。它通常与min-contentmax-content值结合使用,以创建灵活且响应式的布局。

  • 实际上,这意味着框架利用可用空间,确保它永远不会超过max-content的大小。

  • 当在布局盒中与widthheightmin-widthmin-heightmax-widthmax-height的指定尺寸一起使用时,最小和最大尺寸指的是内容的尺寸。

此属性在您希望容器根据其内容扩展或收缩,但仍需设置上限以防止其变得过宽的情况下特别有用。

语法

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

CSS fit-content() - 盒尺寸

接下来

  • 在给出的示例中,box 类width属性的fit-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>    
广告
© . All rights reserved.