Problem encountered when trying to apply background opacity to custom colors using Tailwind CSS and shadcn/ui

While using Tailwind CSS along with the shadcn/ui library for styling buttons, I have encountered an unexpected behavior. The issue arises when trying to add background opacity to a custom color defined in globals.css using HSL values such as:

--primary: 348, 76%, 64%;

The problem occurs when attempting to set the background opacity of a button using this custom color in shadcn/ui. For example:

<button class="hover:bg-primary/90">Button</button>

The goal is to create a button with a hover effect that adds 90% opacity to the background color defined as --primary. However, the opacity setting doesn't seem to have any effect, and the button maintains its original opacity.

Even though the custom color is correctly defined and available in the project's global styles, using Tailwind utility classes to apply opacity to it doesn't produce the desired outcome.

Answer №1

When your file is structured like this:

--background: 231 15% 18%;
  --foreground: 60 30% 96%;

  --muted: 232 14% 31%;
  --muted-foreground: 60 30% 96%;

  --popover: 231 15% 18%;
  --popover-foreground: 60 30% 96%;

  --border: 232 14% 31%;
  --input: 225 27% 51%;

  --card: 232 14% 31%;
  --card-foreground: 60 30% 96%;

  --primary: 265 89% 78%;
  --primary-foreground: 60 30% 96%;

  --secondary: 326 100% 74%;
  --secondary-foreground: 60 30% 96%;

  --accent: 225 27% 51%;
  --accent-foreground: 60 30% 96%;

  --destructive: 0 100% 67%;
  --destructive-foreground: 60 30% 96%;

  --ring: 225 27% 51%;
  --radius: 1rem;

Ensure that it no longer uses commas, such as:

--background: 231 15% 18%;
  --foreground: 60 30% 96%;

  --muted: 232 14% 31%;
  --muted-foreground: 60 30% 96%;

  --popover: 231 15% 18%;
  --popover-foreground: 60 30% 96%;

  --border: 232 14% 31%;
  --input: 225 27% 51%;

  --card: 232 14% 31%;
  --card-foreground: 60 30% 96%;

  --primary: 265 89% 78%;
  --primary-foreground: 60 30% 96%;

  --secondary: 326 100% 74%;
  --secondary-foreground: 60 30% 96%;

  --accent: 225 27% 51%;
  --accent-foreground: 60 30% 96%;

  --destructive: 0 100% 67%;
  --destructive-foreground: 60 30% 96%;

  --ring: 225 27% 51%;
  --radius: 1rem;

Answer №2

Here are some things to consider:

  • Make sure the color is defined correctly in the Tailwind configuration. If you are using comma-delimited components, this indicates you are using legacy HSL format, so the color value in the Tailwind configuration should be similar to:
    module.exports = {
      // …
      theme: {
        extend: {
          colors: {
            primary: 'hsl(var(--primary), <alpha-value>)',
          },
        },
      },
      // …
    };
    
  • Check if the file where the code is located is included in the content file globs.
  • Ensure that the declaration for --primary applies to an ancestor element of the <button>.
  • Verify that there are no other CSS styles in the project that could be conflicting with the styling of the <button> element.

For a complete example, see below:

tailwind.config = {
  theme: {
    extend: {
      colors: {
        primary: 'hsl(var(--primary), <alpha-value>)',
      },
    },
  },
};
:root {
  --primary: 348, 76%, 64%;
}
<script src="https://cdn.tailwindcss.com/3.3.5"></script>

<button class="hover:bg-primary/50">Button</button>
<button class="bg-primary">Button</button>

Answer №3

To properly update the code, you should include / <alpha-value> instead of , <alpha-value>. Take a look at the revised snippet below:

module.exports = {
  // …
  theme: {
    extend: {
      colors: {
        primary: 'hsl(var(--primary) / <alpha-value>)',
      },
    },
  },
  // …
};

Answer №4

Dealing with a similar issue, I found a quick solution:

If you're facing problems with your custom colors in your tailwind config, consider using hsla instead of hsl.

For example, change this:

primary: {
      DEFAULT: "hsl(var(--primary))",
      foreground: "hsl(var(--primary-foreground))",
    },

to:

primary: {
          DEFAULT: "hsla(var(--primary))",
          foreground: "hsla(var(--primary-foreground))",
        },

This adjustment factors in the alpha value for better color calculation.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering issues with link functionality on homepage due to React-Router v6 and Material-UI Tab integration

I'm currently working on a homepage that requires different page links. Below you can find the necessary code snippet for setting up the tabs and routes for each page: <li> The tabs are located here - <Link to="/demo">D ...

Launching a Popup in ASP.NET followed by a Redirect

I have a unique custom CSS/HTML popup lightbox along with a form that contains a button. My objective is, upon clicking the button: to open the popup followed by using Thread.Sleep and finally carry out a Response.Redirect to a different page. Do you th ...

What is the best way to implement restful instead of query syntax in a $resource factory?

Recently, I set up a $resource factory like this: (function() { 'use strict'; app.factory('WidgetFactory', [ '$resource', function($resource) { return $resource('http://localhost:8282/widget/:widgetId&apo ...

What is the technique for hiding the bottom tab navigator upon leaving a specific screen in React Native version 5?

In the home screen, I want only the bottom tab navigator to be visible, and then hidden until the user returns to the home screen. The example provided below is tailored for working in the App.js file, but my situation is different. const Tab = createBot ...

Reading properties of undefined in React is not possible. The log method only functions on objects

I'm currently facing an issue while developing a weather website using the weatherapi. When I try to access properties deeper than the initial object of location, like the city name, it throws an error saying "cannot read properties of undefined." Int ...

Transfer data from a Django template populated with items from a forloop using Ajax to a Django view

Struggling to implement a click and populate div with ajax in my django e-commerce app. The function involves clicking on a category in the men's page which then populates another div. gender.html {%for cate in cat%} <a href="javascript:getcat()" ...

Converting a PHP array to a JavaScript array causes an issue of undefined variable when attempting to access a PHP array that has

I've been searching through other questions without finding the answer, so I'm reaching out for help with my specific issue. My problem is transferring a php array to a javascript array. In my code editor (phpStorm), I'm getting an error st ...

Submitting a nested JSON object in an AJAX request

When it comes to passing nested JSON through AJAX, the format of the sample request should be like this: { 'user': { 'email': email, 'password': password } } login(){ var email=document.getElementById(& ...

What is the method for obtaining multiple indices on an Array?

Attempting to find multiple index positions in an Array for a Boolean value. Experimenting with while and for loops to iterate through more than one index position without success so far. Below is the code snippet: let jo = [1,2,3,4,5] let ji = [1,2,3] ...

Adjust the attributes of THREE.tubeGeometry

Within my Three.js scene, I currently have a tube object that I need to dynamically adjust the start and end points of. I believe this approach is more efficient than creating a new tube with updated points and removing the old one. If this is not the case ...

Is the memory usage of node.js proportional to the number of concurrent requests, or is there a potential memory leak?

Running the following node.js code: var http = require('http'); http.createServer(function(req,res){ res.writeHead(200,{'Content-Type': 'text/plain'}); res.write("Hello"); res.end(); }).listen(8888); Upon starting the server ...

How to Adjust Overlapping Text in CSS?

Currently, I am facing an issue with an element overlapping in my CSS file. On a regular browser, one line of text appears fine but on mobile devices, it overlaps into two lines. This problem is specifically for the mobile version of the website, particula ...

Limit the movement of objects in a canvas using React Three Fiber

Exploring the world of Threejs and react-three-fiber, I am wondering how to keep an object locked in place within the canvas. Even when the perspective camera rotates and moves, I want this object to remain stationary with fixed position and rotation. htt ...

What's the suitable data type for a React component that has unpredictable properties?

Looking to implement a similar component structure: <toolProperties.ToolElement onGenerate={onGenerate} postData={postData} status={status} setStatus={setSta ...

Executing JavaScript functions within Vue JS components

I'm currently working on a project that involves Vue JS within a Laravel Project Can someone guide me on how to fetch data from another JS file? Here's what I have so far: MainComponent.vue data() { return this.getData() } DataComponent.j ...

Initiating CSS animation from the start

Having an issue with the "Start button" that plays both animation and background sounds. When I pause it, the animation does not stop where it left off and starts from the beginning again. I tried using animation-play-state: pause and animation-fill-mode: ...

Tips on transitioning between two tables

Recently, I created an HTML page entirely in French. Now, I am attempting to incorporate a language translation feature on the website that allows users to switch between French and English (represented by two flag icons). My concept involves using a tabl ...

Issue encountered in TypeScript: Property 'counter' is not found in the specified type '{}'.ts

Hey there, I'm currently facing an issue while trying to convert a working JavaScript example to TypeScript (tsx). The error message I keep encountering is: Property 'counter' does not exist on type '{}'.ts at several locations wh ...

What is the reason the child component is not being displayed?

The code within the APP.js component looks like this: import React from "react"; import Exam from "./exam.js"; export default function App() { return ( <Exam> <h1>hashemi</h1> </Exam> ); } Similarly, the ...

Shopify module is throwing an error stating that React is not defined

I wanted to create my first Shopify module, but I encountered an error in my application page on the shop while using React. https://i.sstatic.net/Q02yM.png Here is my index.js code: import {Page} from "@shopify/polaris"; import {ResourcePicker ...