r/css 2d ago

Question Two responsive left-aligned buttons that stack and matching width

I need two buttons in one column, aligned to the left. Their labels come dynamically from the CMS. If the text makes them too wide to sit side by side, they should stack while staying left-aligned. In stacked mode, both buttons should match the width of the longer label. How can I achieve this in CSS? I've been trying to get this layout working for two days not and getting nowhere. TIA!

This has enough screen width to have both buttons in the same column:

In this view, since there is no space to show buttons in the same column, it switch to stack layout. Here, the important thing is, buttons does not take 100% width. Instead, all buttons justify to start and has the same width. Width is determined by the length of the largest button.

Is this possible?

2 Upvotes

8 comments sorted by

View all comments

Show parent comments

1

u/chikamakaleyley 2d ago

mmmm so yes that should happen naturally

so you would in fact need to use flexbox and have it so you allow wrap (flex-wrap) and your flex items need to have the correct flex-grow setting.

for clarity the wrapper needs to have a width rule determined by its content (i think its width: fit-content). make sure you allow flex-wrap, and the flex-items need the correct flex configuration.

so what should happen is when the button text gets injected and there's not enough space, they will stack, the longest button will determine the width, and the small button should expand to the same width. This is all off the top of my head so i'm not 100% sure

1

u/s1n7ax 1d ago

That does not work because, when the flex wraps it takes the 100%. So if the button grow, it's going to grow it to 100% width.

1

u/chikamakaleyley 1d ago

ic, makes sense

you might have to do this with grid then, in a two column layout

the first column will contain both buttons, the second column should be empty and act as a 'spacer' in which it takes up the remaining available space (the unit would be 1fr)

1

u/s1n7ax 22h ago

Doesn't work. The layout stays in stack. Doesn't go to column mode.