Reputation: 1569
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>
Upvotes: 3
Views: 6802
Reputation: 1388
Well I'm afraid this is going to be downvoted, but I read the arguments for/against using tables for layout. I came here after reading those arguments... one of which is "less code", however in this case it looks like possibly more code which is also more complicated to understand.
I also struggled to get columns aligned across multiple rows.
I read the accepted answer, looked at the other responses, then went back, removed my div's and used a table.
There are situations where a table is just plain old easier.
Upvotes: 2
Reputation: 372029
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>
Upvotes: 6
Reputation: 9561
May not be the right solution, but a suggestion/work around !!
Suggestion 1:
<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: 1;visibility: hidden">B</button>
<button style="flex: 1">B</button>
<button style="flex: 1">C</button>
<button style="flex: 1">D</button>
</div>
</div>
Suggestion 2:
<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: 1; margin-left: 25%">B</button> <!-- 25% = 100/(No. of buttons in previous row) -->
<button style="flex: 1">C</button>
<button style="flex: 1">D</button>
</div>
</div>
Upvotes: 1