Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two equal width columns (where the width is set by the longest one) and a third one fills the remaining space

Tags:

I want to make a layout like this, using CSS Grid if possible but open to other possibilities:

enter image description here

Basically, I want to have a container .grid that contains 3 elements (input, btn1, btn2). Firstly, btn1 and btn2 width should be the same and is determine by whichever element needs more space (i.e longer content). After that, the remaining element (input) should take all what is left. I came up with this snippet but for sure it cannot work.

.grid {
  display: grid;
  grid-template-columns: auto 1fr 1fr;
}
<div class="grid">
  <input />
  <button>Foo</button>
  <button>Bar Bar Bar</button>
</div>

What is a good way to achieve this using CSS only?

like image 308
Luke Vo Avatar asked Mar 26 '20 13:03

Luke Vo


People also ask

How do you make grid columns the same width?

If you really need the columns to be the exact same width you should use: grid-template-columns: repeat(3, minmax(0, 1fr)); minmax(0, 1fr) allows the grid tracks to be as small as 0 but as large as 1fr , creating columns that will stay equal.

How do you divide flex into two equal columns?

Approach: To create a two-column layout, first we create a <div> element with property display: flex, it makes that a div flexbox and then add flex-direction: row, to make the layout column-wise. Then add the required div inside the above div with require width and they all will come as columns.

What is grid-template columns?

Definition and Usage. The grid-template-columns property specifies the number (and the widths) of columns in a grid layout. The values are a space separated list, where each value specifies the size of the respective column.


1 Answers

Use a nested grid container for the buttons.

.grid {
  display: grid;
  grid-template-columns: 1fr auto; /* see note 1 */
}

.button-container {
  display: grid;
  grid-template-columns: 1fr 1fr; /* see note 2 */
}
<div class="grid">
  <input />
  <div class="button-container">
    <button>Foo</button>
    <button>Bar Bar Bar</button>
  </div>
</div>
<br>
<div class="grid">
  <input />
  <div class="button-container">
    <button>Foo</button>
    <button>Bar Bar Bar Bar Bar Bar</button>
  </div>
</div>
<br>
<div class="grid">
  <input />
  <div class="button-container">
    <button>Foo</button>
    <button>Bar Bar Bar Bar Bar Bar Bar Bar Bar</button>
  </div>
</div>

Notes:

  1. 1fr on the first column consumes all available horizontal space, pinning the second column to the right as much as possible.

  2. 1fr 1fr on the nested columns causes the horizontal space in the sub-container to be equally divided, regardless of content width.

like image 154
Michael Benjamin Avatar answered Oct 02 '22 07:10

Michael Benjamin