I changed my Portfolio page to use CSS Grid and it was quite easy to use :nth-of-type to change the column display order.
When I changed the theme on this site I wanted to change the portfolio layout. I liked the alternating left/right layout on the front page of the Atmosphere Pro theme.
My initial effort used 1/3 and 2/3 columns, with the portfolio info in the narrow column and the website screenshot in the wide column. It alternated putting the wide column first on every second row. While this worked I didn’t like that it required changing the content order in the source code. Nor did I like that I had to duplicate the html code involved for each row. It would make maintenance error prone (even though it would not be likely to change).
CSS Grid – Check WP_Query current_post
Over the last 6 or so months I have seen many articles raving about the CSS Grid and how it rendered ‘float‘ obsolete. I saw that the displayed order could be specified so I decided to give it a try.
The loop is simpler with just one block of html for both row types (info/image and image/info). I add a class to the container to distinguish the alternate rows.
The CSS is also quite simple. I only apply it when the browser window is 768px or wider as it is okay for each block to be full width for smaller screen sizes. I used a 30%/70% column and a small space (0.5em) between the columns. For the “.alternate” columns I change the column widths to 70%/30% and change the order, putting the image first.
CSS Grid – nth-of-type
After I writing the above code I started thinking about whether I could use :nth-child to target the alternate rows. I added a wrapper div around the portfolio blocks but I didn’t get it to work (I didn’t try very hard). While reading about :nth-child on css-tricks.com I read about :nth-of-type there.
I removed the wrapper div, the $wp_query->current_post check and the .alternate class (and $post_classes array) and came up with this CSS:
The loop is slightly shorter because the $wp_query->current_post check block is gone.
I am very happy with this. The code is so simple, so light. The CSS grid is impressive.