June 25, 2025

Animating grid-template-columns with CSS

Demo

Code

tsx

import { useState } from "react";
import styles from "./gallery.module.css";
export function Gallery() {
const items = [
{
title: "Item 1",
bgColor: "#111111",
},
{
title: "Item 2",
bgColor: "#444444",
},
{
title: "Item 3",
bgColor: "#888888",
},
];
const [gridTemplateColumns, setGridTemplateColumns] =
useState("10fr 1fr 1fr");
return (
<div
className={styles.gallery}
style={{
gridTemplateColumns,
}}
>
{items.map((item, i) => (
<button
type="button"
key={item.title}
onClick={() => {
if (i === 0) setGridTemplateColumns("10fr 1fr 1fr");
if (i === 1) setGridTemplateColumns("1fr 10fr 1fr");
if (i === 2) setGridTemplateColumns("1fr 1fr 10fr");
}}
style={{
backgroundColor: item.bgColor,
}}
></button>
))}
</div>
);
}

css

.gallery {
display: grid;
height: 400px;
gap: 8px;
transition: .3s ease-out grid-template-columns;
button {
min-width: 40px;
}
}

Notes

  • Only works when the units of grid-template-columns are the same e.g. animating from fr -> fr and not fr -> px