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;
		}
	}
}

Bill Erickson

Bill Erickson is the co-founder and lead developer at CultivateWP, a WordPress agency focusing on high performance sites for web publishers.

About Me
Ready to upgrade your website?

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

Let's Talk

Reader Interactions

Comments are closed. Continue the conversation with me on Twitter: @billerickson

Comments

  1. Leonardo Borsten says

    I just found this great solution to the same problem I was having. I googled “css grid last item centered” and this post was the first in the search results.
    Thank you, you saved my day!

  2. Alan says

    This is great. You say “However, I only recommend using this for two or three columns because it will only enter if the last row is short by one.” is there a solution that allows say a 3 col short by 2 i.e. 3 with the 4th centred?