Search code examples
cssflexboxcss-grid

How can you make the button automatically pop to the next row when label becomes too large?


I have two buttons. If there is a space both button should take up 1fr of the space. So they will be placed next to each other. However if the button becomes too large it should take up the full space and put the other button below it, also expanding to full space (as there is no other button competing for space).

I now explicitly said minimum of 100px, but that won't work of course, I tried min-content, max-content, I tried everything but can't seem to get it to work.

.grid 
{
  display: grid;
  grid-gap: 5px;
  grid-template-columns: repeat( auto-fit, minmax( 140px, 1fr ) );
  
  width: 300px;
  margin: 0 auto;
}

.button
{
  padding: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align:center;
  color: #fff;
  background: #000;
  width: 100%;
  box-sizing: border-box;
}

.grid-two
{
  margin-top: 30px;
}

.grid-two .button
{
  background: red;
}

.grid-three
{
  margin-top: 30px;
  grid-template-columns: repeat( auto-fit, minmax( 0px, max-content ) );
}

.grid-three .button
{
  background: green;
}
<div class="grid grid-one">
  <div class="button">Button A</div>
  <div class="button">Button B</div>
</div>

<div class="grid grid-two">
  <div class="button">Button With Large Title</div>
  <div class="button">Button B</div>
</div>

<div class="grid grid-three">
  <div class="button">Button With Large Title</div>
  <div class="button">Button B</div>
</div>
 
 


Solution

  • Flexbox can do this:

    .grid {
      display: flex;
      flex-wrap:wrap;
      gap: 5px;
      width: 300px;
      margin: 0 auto;
    }
    
    .button {
      /* this will do the trick */
      flex-basis:calc(50% - 5px); /* we consider the gap */
      white-space:nowrap;
      flex-grow:1;
      /**/
      padding: 10px;
      display: flex;
      align-items: center;
      justify-content: center;
      text-align: center;
      color: #fff;
      background: #000;
      box-sizing: border-box;
    }
    
    .grid-two .button {
      background: red;
    }
    
    .grid-three .button {
      background: green;
    }
    <div class="grid grid-one">
      <div class="button">Button A</div>
      <div class="button">Button B</div>
    </div>
    
    <div class="grid grid-two">
      <div class="button">Button With Large Title</div>
      <div class="button">Button B</div>
    </div>
    
    <div class="grid grid-three">
      <div class="button">Button With Large Title</div>
      <div class="button">Button B</div>
    </div>