Search code examples
htmlcssflexboxcss-grid

Set width of buttons same as the button with maximum width in the row


I have a container div.parent and it has some button elements. The number of button elements at any given point of time are variable (they may change). The div.parent is currently display: flex with flex-direction: row and some other basic css properties.

So, if there are say, four buttons in the row at a given time, each obviously would have its own width according to the content in it. Say, the widths are 55px, 72px, 78px, 60px. This does not fit well with the design language. I want all the buttons to have same width so that they look better. So, in this case, I would want that all the buttons have a width of 78px which is the maximum. (Because choosing another width, say 72px would not look good on the button with 78px width, so we always choose the maximum.)

I tried using display: flex and could not find a way in css to automatically adjust the width of the button according to the maximum width. Also, I was willing to use table but as per the semantics, it is meant to use for tabular data, not decoration. Cannot even think of a way to lay the buttons out using display: grid.

Here is a demonstration of how I want the buttons to be arranged. Note that, here I manually set the widths of the button, but I need an automatic css layout that sets the button width equal to the maximum width button.

.parent {
  display: flex;
  flex-direction: row;
  align-items: center;
  background: #ddddff;
  padding: 10px;
  margin-top: 20px;
}

.parent button {
  margin: 0 4px;
  width: 120px;
}
<h2> How I want it </h2>
<span>All the buttons should have the same width, and the width should equal to maximum of the widths of all the buttons. In this case, I manually set the button width.</span>
<div class="parent">
  <button> Button </button>
  <button> Another Button </button>
  <button> Yet Another </button>
</div>

How can I achieve it using CSS?


Solution

  • Can be done using CSS grid

    .parent {
      display: inline-grid;
      grid-auto-flow: column;
      grid-auto-columns: 1fr;
      background: #ddddff;
      padding: 10px;
      margin-top: 20px;
    }
    
    .parent button {
      margin: 0 4px;
    }
    <h2> How I want it </h2>
    <span>All the buttons should have the same width, and the width should equal to maximum of the widths of all the buttons. In this case, I manually set the button width.</span>
    <div class="parent">
      <button> Button </button>
      <button> Another Button </button>
      <button> Yet Another </button>
    </div>