Pretty notable when a tweet about a flexbox layouts gets 8K+ likes on Twitter!
4 layouts for the price of 1, thanks flex 👍
— Adam Argyle (@argyleink) January 14, 2020
css`
form {
display: flex;
flex-wrap: wrap;
& > input {
flex: 1 1 10ch;
margin: .5rem;
&[type="email"] {
flex: 3 1 30ch;
}
}
}
`
view source on Codepen 👇https://t.co/Q8H5ly2ZIe pic.twitter.com/y6HqxClILZ
That’s “native” CSS nesting in use there as well, assuming we get that at some point and the syntax holds.
There was some feedback that the code is inscrutable. I don’t really think so, to me it says:
- All these inputs are allowed both to shrink and grow
- There is even spacing around all of it
- The email input should be three times bigger than the others
- If it needs to wrap, fine, wrap.
A great use case for flexbox, which is the right layout mechanism when you aren’t trying to be super precise about the size of everything.
There is a blog post (no byline 🤷♂️) with a more longwinded explanation.
This reminds me a lot of Tim Van Damme’s Adaptive Photo Layout where photos lay themselves out with flexbox. They don’t entirely keep their aspect ratios, but they mostly do, thanks to literally the flexibility of flexbox.
Here’s a fun fork of the original.
It’s like a zillion layouts for the price of one, and just a few lines of code to boot.
I get how this could seem inscrutable, but I think it’s mostly because we’re less used to seeing the flexbox properties. I’d argue the other ways of achieving this layout (to the extent that you could with media queries, floats, and % widths), are no less inscrutable and way more verbose.
If you don’t use the shorthand, this is a bit easier to read:
THANK YOU. I wish everyone would write CSS in long form – much easier to read, and also more source-control friendly to diff/merge tools. Let a tool do the compression to shorthand :-)
Really the only “strange” thing is the second layout, which is possible only because an input with type button/submit has a slightly smaller content size compared to a regular input, and that makes the second layout possible.
I explain that (and the flex-grow, flex-shrink and flex-basis values) in the blog post you kindly linked (Everything on the Polypane blog is written by yours truly.)