Search code examples
cssflexbox

Would like to have equal widths for my flex item buttons, but not sizing at all


I am trying to size the Sure and Cancel buttons to be the same size. I placed them in a flexbox container with display: flex. Then, I put flex: 1 for .button.sure and .button.cancel, but the flex items are not responding at all.

I am working on the assumption that putting display: flex on the container and then its flex items with flex: 1, should do the trick, but I have no idea why these items aren't responding.

I thought maybe the button tags were causing an error with the flex: 1 declaration, so tried nesting the <button> in <div> and that didn't work too.

Here is what I have:

.icon {
 background-color: lavender;
  height: 42px;
  width: 42px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 50%;
  font-weight: 700;
  font-size: 26px;
  color: royalblue;
}

.prompt {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.buttonbox {
  display: flex;
  background: lavender;
}

.button{ 
  border-radius: 5px;
}

.button.sure {
  background: royalblue;
  color: white;
  flex: 1;
}

.button.cancel {
  background: white;
  color: royalblue;
  flex: 1;
}
<div class="prompt">  
  <div class="icon">!</div>
  <div class="buttonbox"> 
    <button class="button sure">Sure</button>
    <button class="button cancel">Cancel</button>
   </div>
</div>


Solution

  • Replace your flexbox with grid. If you set the grid-template-columns to 1fr then each child will occupy the same size. More info on CSS tricks and there's a nice video from Kevin Powell

    .icon {
     background-color: lavender;
      height: 42px;
      width: 42px;
      display: flex;
      justify-content: center;
      align-items: center;
      border-radius: 50%;
      font-weight: 700;
      font-size: 26px;
      color: royalblue;
    }
    
    .prompt {
      display: flex;
      flex-direction: column;
      align-items: center;
    }
    
    .buttonbox {
      /*replaced flex with grid */
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      background: lavender;
    }
    
    .button{ 
      border-radius: 5px;
    }
    
    .button.sure {
      background: royalblue;
      color: white;
      /*flex: 1; delete this, not needed*/
    }
    
    .button.cancel {
      background: white;
      color: royalblue;
      /*flex: 1; delete this, not needed*/
    }
    <div class="prompt">  
      <div class="icon">!</div>
      <div class="buttonbox"> 
        <button class="button sure">Sure</button>
        <button class="button cancel">Cancel</button>
       </div>
    </div>