How to Align Form Elements with Flexbox
Here's how you can use flexbox to align your form elements nice and evenly.
Before flexbox came along, aligning form elements could be a bit tricky at times. But flexbox simplifies this process quite considerably. Let's start with a quick example.
Here's a form without flexbox.
This form uses some light formatting, but the input fields are all the same width. This results in the right edge looking a bit jagged as the inputs don't line up directly above each other.
Now, if you're happy with that, fine. There's no need to go any further.
But what if we want to have the input controls extend all the way to the right edge?
Without flexbox, this would be a bit of a pain to get working properly. Especially if the form itself is fluid (i.e. it expands/contracts depending on the width of its parent or viewport). If the form is fluid, then each input control would also need to expand and contract as required. In this case, you couldn't use a fixed width for the input controls because as soon as the form's width changes, the width of the control would be wrong. So you'd need to use a bit of trickery to get it all working correctly.
However, flexbox allows you to do this without having to apply any magic tricks.
To do that, we first set each .form-row
class to display: flex
:
Note that we also used justify-content: flex-end
but this is optional. In this case it simply moves the button across to the right.
And now that each form row is a flex container, we apply the following to the input controls:
So by applying flex: 1
to the input controls, flexbox will make these controls use up the available free space, after the labels have been allocated. So the labels remain at their normal width and any padding is retained. The input controls can then start where they normally would, and stretch all the way to the end.
Same-Width Controls
You could modify the above example so that the left edge of the form controls all line up too (as well as the right edge).
Like this:
All we did here was add flex: 1
to the labels, and changed the controls to flex: 2
:
This sets the controls to twice the width of the labels. You can adjust this depending on the form's width/expected width. For example you could use a 1/3 ratio or a 1/4 ratio for wider forms.
If you're using a fixed width form, you can set one ratio that best suits the form. If it's a fluid form that changes width based on the width of the viewport, then you could use media queries to set a different ratio for each breakpoint.
Same-Width Controls but Responsive
Here's an example with media queries that change the ratio as the viewport size changes.
Click on the Preview button to view this form at a larger viewport. Then resize the browser down. You should see the form controls adjusting their width as you shrink the browser window.
This assumes you're not already viewing this on a smaller device. If you are, try this out when you get to a larger one.