Loading...
save

How to prevent layout shift (CLS) when dynamically rendering a responsive multi-column grid in Tailwind CSS?

clock icon

asked 75 days ago

message icon

0

eye icon

10

I am building a responsive dashboard view where items are displayed in a grid layout. Depending on the screen size, the layout shifts from a single-column layout on mobile to a 3-column layout on large desktops.

The problem I am facing is Cumulative Layout Shift (CLS). When the page initially loads on a desktop monitor, the layout flashes a single full-width column layout for a split second before the JavaScript finishes evaluating the responsive breakpoints and snaps the elements into their correct 3-column slots. This sudden visual jump pushes down the surrounding content and hurts the performance score.

Here is my core grid container configuration:

1// components/shared/MetricGrid.tsx
2export default function MetricGrid({ items }: { items: any[] }) {
3 return (
4 // This container undergoes a visual snap during hydration
5 <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
6 {items.map((item) => (
7 <div key={item.id} className="min-h-[150px] rounded-xl bg-gray-100 p-6">
8 <h3 className="text-lg font-semibold">{item.title}</h3>
9 <p className="text-2xl font-bold mt-2">{item.value}</p>
10 </div>
11 ))}
12 </div>
13 );
14}
1// components/shared/MetricGrid.tsx
2export default function MetricGrid({ items }: { items: any[] }) {
3 return (
4 // This container undergoes a visual snap during hydration
5 <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
6 {items.map((item) => (
7 <div key={item.id} className="min-h-[150px] rounded-xl bg-gray-100 p-6">
8 <h3 className="text-lg font-semibold">{item.title}</h3>
9 <p className="text-2xl font-bold mt-2">{item.value}</p>
10 </div>
11 ))}
12 </div>
13 );
14}

0 Answers

Empty state illustration

No Answers Found

The answer board is empty. Make it rain with your brilliant answer.

1

Write your answer here

Top Questions