I recently built a new theme for my website. On the home page and on the blog page, I used Flexbox to create a grid of boxes, 3 boxes to a row on the desktop version. That part was pretty easy. The hard part was to align Flexbox items vertically top to bottom.
It turns out the Flexbox is…very flexible. Using Flexbox for grids is so much easier than using floats and counting nth children to clear floats and padding and all the other hacks that go with float-based grids.
Flexbox Code to Align Flexbox Items Vertically Top to Bottom
The code for this is pretty simple, but it took me a while to figure out the right combination of flex code.
See the Pen Align Flexbox Items Vertically Top to Bottom by Pat Fortino (@pxforti) on CodePen.dark
The following is the css I used to create the Flexbox grid and align the items within each box, H2s and paragraphs, vertically top to bottom.
On line 10 in the css code, the list is declared as flex and content is justified to extra space is divided between the image. By default, when you declare display: flex; the default is to display the items in rows. This makes each li display in a row with extra space divided between them.
On line 20, I declare flex again, but overriding the default row with columns:
flex-flow: column nowrap; This keeps the items aligned vertically. Also, I added justify-content: space-between; to make the items within each li or div to align vertically starting at the top of the container and ending at the bottom of the container.
Finally I used flex: 0 1 28%; which is shorthand for flex-grow, flew-shrink, and flex-basis. Basically, this says to no let the items within the flexbox to grow (so we can use the extra space between them), to shrink if necessary, and to make the item width 28%;
In the HTML code, the first row of boxes uses an unordered list as the flex container. The second row of boxes uses divs as the flex item container. In both the UL and Div, the heading 2 and paragraphs are the flex items that are aligned vertically. The code flex: 0 1 28% applies to the H2 and paragraphs.
Ultimately, the image below is what I wanted to accomplish. In order to get the Read More buttons to align at the bottom of the container box, I had to move them from the end of the excerpt line to a line of their own. That way, they are seen as the last individual flex item and align at the bottom. For more information, see Move Genesis Read More to Entry-Footer.
Leave a Reply