htmlcssflexbox

How to stretch and center an element inside flexbox along cross axis?


I'm trying to get an item in a flexbox layout to fill all available space inside the container if it can, or be centered if it can't due to its max-width/max-height constraints. In the snippet below, it works like I want along the main axis, but not along the cross axis. When using align-items: center, the item is centered, but has minimum size. With align-items: stretch it has maximum size, but is no longer centered. How do I make it work? I'd prefer to avoid additional html elements.

.container {
  background: blue;
  width: 200px;
  height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
  /* align-items: stretch; */
}

.item {
  flex: 1;
  background: red;
  min-width: 20px;
  min-height: 20px;
  max-width: 100px;
  max-height: 100px;
}
<div class="container">
  <div class="item"></div>
</div>


Solution

  • I would define the size differently:

    .container {
      background: blue;
      width: 200px;
      height: 200px;
      display: flex;
      justify-content: center;
      align-items: center;
      
      /* resize the container to debug*/
      resize: both;
      overflow: hidden;
    }
    
    .item {
      width: clamp(20px, 100%, 100px);
      height: clamp(20px, 100%, 100px);
      
      background: red;
      border: 2px solid green;
      box-sizing: border-box;
    }
    <div class="container">
      <div class="item"></div>
    </div>