How to modify CSS variables depending on the parent class: Leveraging the power of Sass and Tailwind CSS

Currently, I am in the process of customizing a Next.js website with Tailwind CSS and working on implementing a theme switching feature utilizing CSS (Sass) variables.

There are two primary modes I am focusing on:

  • Default mode: consisting of light and dark themes.
  • Minimalist mode: also offering light and dark themes but with a more limited color palette (mainly black and white).

As a result, users have four options, and the tailwind color changes based on dynamically provided classes.

Depending on the main div class bg-primary, the color scheme should be as follows:

  • If no class is provided => default light theme, bg-primary = #79A542; // this works fine
  • If "dark" is specified => default dark theme, bg-primary = #03004C; // this works well
  • If "minimalist" is specified => minimalist light theme, bg-primary = #FEFDF8; // this works perfectly
  • If "minimalist dark" is specified => minimalist dark theme, bg-primary = #0f0f0f; // facing issues here

All theme variations seem to be functioning except for "minimalist dark," where the background color is #03004C instead of #0f0f0f. Why is the minimalist dark theme being overridden by the default one?

Here is a snippet from my globals.scss file setting:

@tailwind base;
@import url('https://fonts.googleapis.com/css2?family=Amiri&family=Montserrat&family=Rakkas&family=Roboto&display=swap');
@import url('https://fonts.googleapis.com/css2?family=Aref+Ruqaa&family=Lateef&display=swap');

:root {
/*default mode*/
  --primary:  #79A542;
  --secondary: #CFF0A5;
  --third: #CFF0A5;
  --inverse: #0f0f0f;
  --font-mono: 'Roboto Mono',monospace;
  --font-sans: 'Montserrat', sans-serif;
  & .arabic {
    --font-mono: 'Amiri', serif;
    --font-sans: 'Rakkas', cursive;
  }
  & .dark {
    --primary: #03004C;
    --secondary: #6A1497;
    --third: #E61D6D;
    --inverse: #7C54E1;
  }
}


.minimalist {
/*Minimalist mode*/
  --third: #98999B;
  --inverse: transparent;
  --primary: #FEFDF8;
  --secondary: #0f0f0f;
  & .dark {
    --primary: #0f0f0f;
    --secondary: #FEFDF8;
  }
  & .arabic {
    --font-mono: 'Aref Ruqaa', serif;
    --font-sans: 'Lateef', cursive;
  }
}

@tailwind components;
@tailwind utilities;

This section is from my _app.js file:

import '../styles/globals.css'
import Nav from '../components/Nav'
import { useState} from 'react'

function MyApp({ Component, pageProps }) {
  const [attributes, setAttributes] = useState("minimalist dark") // Themes are changed here

  return (
    <div className={attributes}>
      <main className="bg-primary">
        <Nav/>
      </main>
    </div>
  )
}

export default MyApp

Below is my tailwind.config.js file:

module.exports = {
  purge: ['./pages/**/*.js', './components/**/*.js'],
  darkMode: 'class', // or 'media' or 'class'
  theme: {
    extends: {
    },
    colors: {},
    textColor: {
      primary: 'var(--primary)',
      secondary: 'var(--secondary)',
      third: 'var(--third)',
      inverse: 'var(--inverse)',
      white: 'var(--white)',
      black: 'var(--black)',
    },
    backgroundColor: {
      primary: 'var(--primary)',
      secondary: 'var(--secondary)',
      third: 'var(--third)',
      inverse: 'var(--inverse)',
      white: 'var(--white)',
      black: 'var(--black)',
    },
    fontFamily: {
      'sans': 'var(--font-sans)',
      'mono': 'var(--font-mono)',
    },
  },
  variants: {
    extend: {},
  },
  plugins: [],
}

Is the issue related to reusing the same dark class? How can I resolve this?

Answer №1

If you want to target the class dark within the minimalist class, your CSS selector should be .minimalist .dark. However, if you want to target elements with both the minimalist and dark classes, your selector should be .minimalist.dark without the space.

In SCSS, remember to omit the space between the parent selector (&) and the class name. Here's an example:

.minimalist {
  --third: #98999B;
  --inverse: transparent;
  --primary: #FEFDF8;
  --secondary: #0f0f0f;

  &.dark {
    --primary: #0f0f0f;
    --secondary: #FEFDF8;
  }
}

The default .dark class works fine as it is defined within the :root class.

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

Placing the child element behind the parent element's parent does not seem to be affected by the `z-index`

Please help! I've been struggling to get the <span> to appear behind the #sideBar using z-index: -3, but it's not working as expected.</p> body { margin: 0px; font-family: "Signika Negative", sans-serif; background-color: #25 ...

Issue with jquery .click function not triggering after CSS adjustment

In the process of creating a fun game where two players take turns drawing on a grid by clicking <td> elements. Currently, I have implemented the functionality to toggle the background color of a <td> element from black to white and vice versa ...

Converting coordinates to pixel-based fixed positioning in CSS

After creating an animated square pie chart using basic CSS to display it in a grid format, I am now looking to transform the larger squares into a state map grid. Any ideas on how to achieve this? In my JavaScript code snippet below, I believe there is a ...

Click on the hyperlink to adjust the background size of an inline list item

I created a navigation bar using inline display for the li elements. I want my last column to have a defined height background. However, it is only displaying a background behind the name of the column. Here is the relevant section from style.css: #navi ...

Stop the stacking of 'display:table' specifically on Android devices

I have created a social media menu with several different links. It displays correctly in Chrome, Safari, Firefox, and Internet Explorer on iOS devices, but on Android devices, the icons stack horizontally: Here is the HTML code: <ul id="menu-social"& ...

Tips for utilizing SeleniumRC within JUnit framework for elements with dynamically changing IDs

I'm currently in the process of automating a workflow and I need to click on a link within a table row. The challenge is that all links within the rows share the same element ID, and the source code has a JavaScript code snippet like this: ("Element I ...

Tips for integrating scroll-snap and jQuery's .scroll() function together

I'm facing challenges in integrating both of these elements into the same project. When I activate overflow: scroll, my jQuery function does not work as expected. However, if I deactivate it, then the jQuery works but the scroll-snap feature does not ...

What are the steps to troubleshoot CSS issues in NextJS?

Currently, I am encountering challenges while trying to integrate markdown with CSS. The problem I am facing has been replicated in the link provided: https://codesandbox.io/s/react-quilljsbasic-forked-3rcxw?file=/src/App.js ...

Redirecting with NextAuth on a t3 technology stack

Recently, I set up a new T3 app using the NextJs app router. With NextAuth configured and some providers added, everything appears to be in order. However, once I log in, I keep getting redirected to a link that leads to a non-existent page: http://localho ...

Ways to even out the base of a tilted vessel?

My container is currently transformed with transform: skew(0deg, -3deg )translateY(-6vh), but since I am using it as a footer, I would like the bottom part to be completely flat. Is there a way to achieve this without placing another container on top wit ...

Expanding Grid Container in Material UI to Fill Parent Height and Width

Challenge I'm struggling to figure out how to make a Grid container element expand to the height and width of its parent element without directly setting the dimensions using inline styles or utilizing the makeStyles/useStyles hook for styling. I&ap ...

Avoiding Access-Control-Allow-Origin cors issue when integrating with Stripe

Currently, I am working on setting up a payment system using Stripe. Below is the post request code I am using with Express: try { const session = await stripe.checkout.sessions.create({ line_items: [ { price: `${priceId}`, // M ...

The CSS slideshow is malfunctioning when displaying images retrieved from the database

I received a complimentary website layout to enhance my PHP skills. The website originally had slides on the index page, sourced directly from my computer when it was in index.html. However, now I have modified it to retrieve images from a database. Instea ...

Preserve the video's aspect ratio within a fixed height and width layout by utilizing CSS styling

I am currently in the process of developing a web application with a fixed height layout that does not utilize flexbox and is also limited by width constraints. My goal is to divide the screen in half both vertically and horizontally, around 50% for each ...

Error encountered in the VS Task Runner Explorer: Node Sass failed to locate a binding

When I try to open the Visual Studio Task Runner Explorer, I encounter an issue where the gulpfile.js fails to load, resulting in an error message in the Output window. Failed to run "C:\DATA\Git\MyApp\MyBiz.MyApp\MyBiz.MyApp.Webs ...

What is the reason for preserving the height to width ratio in the <img> tag?

When I write a simple code like this: <img src="mycat.jpg" height="300px";> I noticed that if the image is very large, the height will be reduced to 300px, and the width will automatically adjust to fit the new height. I expected ...

Discover the Magic of Jquery Hover Effect Unleashed

$('.outerBox').hover( function() { $(this) > $('.innerBox').stop(); $(this) > $('.innerBox').slideDown(750); }, function() { $(this) > $('.innerBox').stop(); $(this) > $(&apos ...

Customer uploaded an image to the WordPress header but it is not aligning correctly

Trying to align an image added by my client in the WordPress header. As someone who is still learning CSS, I'm struggling to get it exactly where we want it. Visit the site here The Options House graphic currently sits on the right. My goal is to ha ...

The positioning of the text appears to be in the center, but it is actually

Currently, my text "lorum ipsum" is centered in CSS, but I want to align it to the left and add padding on the right later. Can someone explain what I've created here? #ubba { font-family: "Open Sans", sans-serif; font-size: 20px; ...

Adjust the source of the HTML5 video tag based on the orientation of an iPad

I am currently coding an HTML5 page specifically for iPad Mobile Safari, which includes a video tag for embedding video files. I have successfully implemented CSS3 media queries to determine the orientation of the iPad. My next challenge is to dynamically ...