Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

aligning columns in two rows of flex container

Tags:

html

css

flexbox

I have two rows: one with 4 buttons and one with 3 buttons.

I want the second row's first column to match with the first row's second column in flexbox.

Here is my code, any help is appreciated.

<div> 
  <div style="display: flex"> 
    <button style="flex: 1"> A </button> 
    <button style="flex: 1"> B </button>
    <button style="flex: 1"> C </button> 
    <button style="flex: 1"> D </button> 
  </div> 
  <div style="display: flex"> 
    <button style="flex: 2"> B </button>
    <button style="flex: 1"> C </button> 
    <button style="flex: 1"> D </button> 
  </div> 
</div>
like image 832
Patrick Klitzke Avatar asked Nov 18 '25 11:11

Patrick Klitzke


1 Answers

Try using an invisible flex item in the second row.

For more accurate sizing, use the flex-basis property (similar to width, in this case).

With flex-grow, you'll have a harder time aligning the columns in both rows. flex-grow is more concerned with the distribution of free space than precise sizing of flex items. (More details.)

<div>
  <div style="display: flex">
    <button style="flex: 1 1 25%">A</button>
    <button style="flex: 1 1 25%">B</button>
    <button style="flex: 1 1 25%">C</button>
    <button style="flex: 1 1 25%">D</button>
  </div>
  <div style="display: flex">
    <button style="flex: 1 1 25%; visibility: hidden;">A</button>
    <button style="flex: 1 1 50%">B</button>
    <button style="flex: 1 1 12.5%">C</button>
    <button style="flex: 1 1 12.5%">D</button>
  </div>
</div>

jsFiddle

like image 99
Michael Benjamin Avatar answered Nov 20 '25 01:11

Michael Benjamin