Spotify-Esque Layout with CSS

At work recently I struggled to create a CSS grid layout similar to Spotify. The criteria is as follows:

  • The gap between grid columns and rows should be static
  • The aspect ratio of the grid item should be static
  • The leftmost grid item should spread fully to the left side of the parent container, the rightmost grid should spread fully to the right side of the parent container.
  • Grid items should stay within a minimum width, and ‘add more columns’ as the viewport expands.

In other words, items should fill the space of the parent container and maintain aspect ratio.

The recipe to achieve this is as follows.

The parent container element should use CSS grid.

  • Use justify-content: space-between to make the items spread fully to the left and right bounds of the container
  • The grid template columns is the real juice behind the layout:

    • the repeat allows us to not have to explicitly set the number of columns,
    • minmax(215px, 1fr) says “a column must be at least 215px, otherwise it’s one fr”. One fr unit is like saying “each column is an equal fraction”.
.grid-parent {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(215px, 1fr));
  justify-content: space-between;
  grid-gap: 10px;

Next, the child element needs to follow this formula:

The only thing to note here is the aspect-ratio css attribute. Use whatever ratio you need here — it will set the width/height of the element based on the constraints of the grid and the minmax width, rather than relying on you needing to manually manage the width of the element.

.grid-child {
  aspect-ratio: 1/1;
  width: 100%;
  height: 100%;

And yep. That’s pretty much it! Here’s a small demo:

Last modified: July 22, 2023
© 2024