Reordering pagination with flexbox

May 24, 2016,   |   Front End
Agile League

I’ve been learning more and more rails development since I became the Agile League’s designer, but I still have a hard time leaving css solutions behind. Recently I implemented the will_paginate gem into a project. It’s a great gem for adding pagination with ease to your view. The instructions are easy to follow, that I was able to add the pagination to the controller and view without a single problem.  The pagination comes in unstyled unless you include a few of their pre-generated css:pagination

The problem I ran into is that my original design called for pagination to look and flow a little differently:

intended flexbox reordering

Without diving too deeply in to the documentation and tackling more rails code than I’m comfortable with, I didn’t know how to get the next and previous buttons right aligned. Enter my experience working on ThimbleCSS and flexbox knowledge. The basic html output looks like:

<div class="pagination"><span class="previous_page disabled">&lt;</span> <em class="current">1</em> <a href="/?page=2" rel="next">2</a> <a href="/?page=3">3</a> <span class="gap">…</span> <a href="/?page=190">190</a> <a class="next_page" href="/?page=2" rel="next">&gt;</a></div>

I thought about float right for the .previous_page and .next_page elements, but that creates an ordering problem, and I didn’t want to add some odd position absolute on elements when I didn’t have to to fix this. Since pagination can act as a flexbox container, and the children elements don’t have any children elements of their own, by adding a few simple lines of css, I was able to make the whole thing flex with ease:

.pagination {
  display: flex;
  flex: 1 1 auto;
  clear:both;
  * {
    display:block;
  }
}

From here it was a simple matter of telling the .previous_page and .next_page to order at the end of the flow with a simple flex ordering:

.previous_page, .next_page {
  order:1000;
}
.previous_page {
  margin-left:auto;
}

By allowing the previous page to have a margin-left:auto, it will fill the space available as a flex child and push itself and the next element to the far right. From here it was a simple matter of applying the basic rounded corners and drop shadows. A few lines of css and a few minutes and I was able to match the final project perfectly to my design:

live reordered flex pagination

This is one simple and great example of the power of flexbox reordering. The real power also comes in the ability to reprioritize an entire sites’s flow and emphasis based on screen size.