I’m working on a responsive grid layout using Tailwind CSS and want to style grid items differently based on the screen size.
Here’s a simplified example of my code:
<html lang="en">
<head>
<script src="https://unpkg.com/@tailwindcss/browser"></script>
</head>
<body class="bg-gray-800">
<section class="container mx-auto my-10 text-white">
<div class="grid grid-cols-2 gap-10 text-white xl:grid-cols-4 [&>*:nth-child(2n+1)]:bg-blue-500 xl:[&>*:nth-child(4n+1)]:bg-blue-500">
<div class="size-20 bg-gray-600">1</div>
<div class="size-20 bg-gray-600">2</div>
<div class="size-20 bg-gray-600">3</div>
<div class="size-20 bg-gray-600">4</div>
<div class="size-20 bg-gray-600">5</div>
<div class="size-20 bg-gray-600">6</div>
<div class="size-20 bg-gray-600">7</div>
<div class="size-20 bg-gray-600">8</div>
<div class="size-20 bg-gray-600">9</div>
<div class="size-20 bg-gray-600">10</div>
</div>
</section>
</body>
</html>
What I’m trying to achieve:
Below
xlscreens (default): Make every odd item (1, 3, 5, 7, 9) blue.At
xlbreakpoint: Only make every 4th starting at 1 (1, 5, 9) blue.
The issue:
When I resize to xl screens, both selectors apply at the same time.
So instead of only 1, 5, 9 being red, I get 1, 3, 5, 7, 9.
It looks like Tailwind’s xl: prefix doesn’t override the base [&>*:nth-child()] rule, and both are active.
Question:
How can I properly switch nth-child selectors at different Tailwind breakpoints so that only the desired styles are applied per breakpoint?