By Ralph and Karen Menezes
Ever struggle with CSS to create vertical centering or equal heights on a web app layout? We have. Thankfully our collaborator and front-end developer Karen Menezes has some answers. She’s published a sweet and fairly in depth article on Smashing Magazine looking into flexbox, a simple and accommodating solution for just such fuss. It’s chock-full of real world use cases and info on browser support.
Here’s a sample:
A. VISUAL ORDER INDEPENDENCE WITH FLEX DIRECTION
Use case: I have a sidebar positioned to the right of the main content section. On small screens, I want the sidebar to be at the top of the main content, reversing the order.
Issue: I don’t want to use JavaScript or a CSS hack to change the visual order.
Discussion: Flexbox is agnostic about the order in a layout. This makes it a miraculous tool for responsive layouts. We can do this in two ways: using the flex-direction property or the order property. Let’s look at the first option here.
Solution: Let’s build the layout with the sidebar as the first section in our markup. This is logical for two reasons: It adheres to the principle of a mobile-first layout, and it is beneficial to screen readers because the sidebar links are first in the source order. Let’s declare flex-direction: column on the parent (because row is the default). In our media query for large screens, we’ll change flex-direction to row-reverse, which solves our issue.
As a bonus, we’ll throw in a fixed-width sidebar (which is always 180 pixels on large screens and full width on mobile).
See the Pen Flexbox: Sidebar with source order independence using flex-direction by Karen Menezes (@imohkay) on CodePen.
You can read the full article over at Smashing Mag.