Search code examples
htmlcsstailwind-css

Tailwind border shows colors wrong with gradient


I have a <div class="hover:shadow-primary/25 hover:border-primary box-border flex h-full flex-col justify-center rounded-2xl border-4 border-transparent bg-gradient-to-br from-[#180042] via-[#2e017d] to-purple-900 p-20 text-white shadow-xl duration-100 ease-in-out hover:border-4 lg:col-span-2 lg:row-span-2 lg:bg-gradient-to-br"></div> As you can see there is a weird color shift at the borders. I have a transparent border to avoid content shifting when I hover over it.

enter image description here enter image description here

How can I either avoid the shifting of content when I hover the div or avoid the color shifting at the border?


Solution

  • You could consider reworking the background gradient such that it covers the border box size of the element. This involves moving its "origin" point to the top-left corner and increasing its size by the border width on all four sides:

    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: 'red',
          },
        },
      },
    }
    <script src="https://cdn.tailwindcss.com/3.4.5"></script>
    
    <div class="
      hover:shadow-primary/25 hover:border-primary box-border flex h-full flex-col justify-center rounded-2xl border-4 border-transparent bg-gradient-to-br from-[#180042] via-[#2e017d] to-purple-900 p-20 text-white shadow-xl duration-100 ease-in-out hover:border-4 lg:col-span-2 lg:row-span-2 lg:bg-gradient-to-br
      bg-[length:calc(100%+(theme(borderWidth.4)*2))_calc(100%+(theme(borderWidth.4)*2))]
      bg-[position:calc(theme(borderWidth.4)*-1)_calc(theme(borderWidth.4)*-1)]
    ">Foo</div>

    Alternatively, you could also consider using Tailwind's ring-* set of utilities to draw the border on hover:

    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: 'red',
          },
        },
      },
    }
    <script src="https://cdn.tailwindcss.com/3.4.5"></script>
    
    <div class="
      hover:shadow-primary/25 box-border flex h-full flex-col justify-center rounded-2xl bg-gradient-to-br from-[#180042] via-[#2e017d] to-purple-900 p-20 text-white shadow-xl duration-100 ease-in-out lg:col-span-2 lg:row-span-2 lg:bg-gradient-to-br
      hover:ring-primary hover:ring-inset hover:ring-4
    ">Foo</div>