Tailwind: Change the bg-gradient of div with dark mode

48 Views Asked by At

I'm learning tailwind and I have this div :

<div class="mt-5 border border-gray-300 p-2 bg-gradient-to-b from-gray-100 via-purple-50 to-gray-50 rounded-lg mb-8 p-4 dark:bg-black">

And in dark mode my background is still the original gradient (my dark mode is working)

I want a black background in dark mode.

I noticed that If I did this :

<div class="mt-5 border border-gray-300 p-2 bg-gradient-to-b from-gray-100 via-purple-50 to-gray-50 rounded-lg mb-8 p-4 bg-gradient-to-b from-green-200 via-pink-100 to-red-500">

It's the second gradient (bg-gradient-to-b from-green-200 via-pink-100 to-red-500) which is used.

But if I did this :

<div class="mt-5 border border-gray-300 p-2 bg-gradient-to-b from-gray-100 via-purple-50 to-gray-50 rounded-lg mb-8 p-4 bg-black">

That's not the bg-black which is used but the bg-gradient-to-b.

So maybe it's linked :)

2

There are 2 best solutions below

4
ADITYA On

To ensure that the background color in dark mode is black, you can try adding the dark:bg-black class directly to your div.

   <div class="mt-5 border border-gray-300 p-2 bg-gradient-to-b from-gray-100 via-purple-50 to-gray-50 rounded-lg mb-8 p-4 dark:bg-black">
3
elemes On

You are experiencing this issue because bg-gradient works like adding a background image to a div. Whereas, bg-black is just background-color. Gradient takes priority over background color.

So I tested your code and added dark:bg-none to clear out the gradient set for light mode and it works. Here's the updated code:

<div class="mt-5 border border-gray-300 p-2 bg-gradient-to-b from-gray-100 via-purple-50 to-gray-50 rounded-lg mb-8 p-4 dark:bg-black dark:bg-none">
</div>

Edit: Tailwind Play Link enter image description here

Hope this helps.