CSS Grid – Center Last Item

CSS Grid is wonderful for building multi-column layouts, but if you have one less item in your grid than you expected, it will look off balance.

To center the last one, you can double the number of columns to 4 and set each item to span 2. If the last item is odd, start on the second column so it spans columns 2 and 3.

.grid {
	display: grid;
	grid-template-columns: repeat( 4, 1fr );
}

.item {
	grid-column: span 2;
}

.item:nth-last-child(1):nth-child(odd) {
	grid-column: 2 / span 2;
}

With a bit of math and SCSS, this can be generalized to work with any number of columns.

However, I only recommend using this for two or three columns because it will only center if the last row is short by one.

.grid-on-left {
	@include grid-center-last( 2 );
}

.grid-on-right {
	@include grid-center-last( 3 );
}

@mixin grid-center-last( $columns ) {
	$total_columns: $columns * 2;
	$span: $total_columns / $columns;
	$offset: $columns - 1;
	$nth-child: if( $columns % 2 == 0, 'odd', 'even' );

	display: grid;
	grid-template-columns: repeat( $total_columns, 1fr );

	& > * {
		grid-column: span $span;

		&:nth-last-child(#{$offset}):nth-child(#{$nth-child}) {
			grid-column: $span / span $span;
		}
	}
}

WordPress Development

Bill Erickson

Bill Erickson is a freelance WordPress developer and a contributing developer to the Genesis framework. For the past 14 years he has worked with attorneys, publishers, corporations, and non-profits, building custom websites tailored to their needs and goals.

Ready to upgrade your website?

I build custom WordPress websites that look great and are easy to manage.

Let's Talk

Reader Interactions

Comments

Leave A Reply