Guide to transforming Tailwind CSS into a class and saving it in a CSS document

Recently, I implemented Tailwind CSS to style my application. It has been a helpful tool, but I am looking to consolidate all the CSS into one file for better organization. I want to keep it separate from the HTML code.

My attempt to convert the following div element:

<div className="relative w-9 h-5 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 dark:peer-focus:ring-blue-800 rounded-full peer dark:bg-gray-700 peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all dark:border-gray-600 peer-checked:bg-blue-600"></div>

using the command below (added to my app.css file):

.checkbox-style {
  @apply relative w-9 h-5 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 dark:peer-focus:ring-blue-800 rounded-full peer dark:bg-gray-700 peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all dark:border-gray-600 peer-checked:bg-blue-600;
}

Unfortunately, this approach did not work as expected and I encountered an error stating unknown rule at apply. Is there a way to fix this issue?

For context, I am currently using Tailwind CSS version 3.4.1 in combination with React version 18.2.0.

Answer №1

Using Tailwind CSS @apply directive for applying intricate styles can be more challenging than simply copying and pasting utility classes from the element to the CSS file. The @apply directive is not compatible with styles that include:

  • content, like ::before and ::after selectors
  • pseudo-classes such as :checked
  • complex variant styles.

To make your code more manageable, consider refactoring it in this way:

HTML

<div className="checkbox-style"></div>

CSS

.checkbox-style {
  @apply relative w-9 h-5 bg-gray-200 rounded-full dark:bg-gray-700;
}

.checkbox-style:after {
  @apply absolute top-2 start-2 bg-white border-gray-300 border rounded-full h-4 w-4 transition-all;
}

.checkbox-style:focus-within {
  @apply outline-none ring-4 ring-blue-300 dark:ring-blue-800;
}

.checkbox-style:checked {
  background-color: #3182ce; /* blue-600 */
  transform: translateX(100%);
}

.checkbox-style:checked:after {
  border-color: white;
}

Although the @apply directive with the peer variant in Tailwind may not function as expected in certain cases due to its complexity. Consider using:

JavaScript or React to manage the checkbox state and apply styles based on its state

import React, { useState } from "react";
import "./App.css";

function App() {
  const [isChecked, setChecked] = useState(false);
  
  const toggleChecked = () => {
    setChecked(!isChecked);
  };

  return (
    <div 
      className={`checkbox-style ${isChecked ? "checked" : ""}`}
      onClick={toggleChecked}
    ></div>
  );
}

export default App;

Keep them inline, as you are currently doing.


Tailwind CSS Just-In-Time (JIT) allows for dynamic creation of styles through JavaScript, enhancing the management of pseudo-classes.

When using the peer variants, you define a state at an element's level but wish to apply a style to a "peer" element. However, even with JIT, the peer and peer-checked variants perform best with inline utility styles rather than in your CSS files where @apply directive is utilized.

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

The Bootstrap Dynamic Navbar is not adjusting for mobile devices because of the addition of a logo

Struggling to incorporate a logo into the navbar of my website. It looks good on larger screens, but causes the navbar to break on smaller screens. View without the logo: Click Here View with the logo and resizing issues: Click Here I think I can make th ...

Set the value obtained from a resolved promise to a mutable reference object in a React component

I am in the process of developing a random movie generator. I am utilizing an external API to retrieve a list of movies and then selecting one randomly from the returned data. The current implementation is as follows: export default function Page() { con ...

What is the reason behind the router.query not functioning correctly in the app/ directory with page.js, but functioning properly when relocated to the pages/ directory with index.js

When I attempted to utilize router.query inside my app directory, it was null. However, when I moved to a new pages directory outside the app, it worked but required the file name to be changed to index.js. This resulted in the NextUI component being unabl ...

Turn off images using Selenium Python

In order to speed up the process, I believe that disabling images, CSS, and JavaScript can help since Webdriver waits for the entire page to load before moving on. from selenium import webdriver from selenium.webdriver.firefox.firefox_profile import Firef ...

Conceal user input field in React using a hook

I am looking for assistance with a form that has 4 input fields: username, password, email, and mobile. My goal is for the email field to disappear if an '@' symbol is typed in the username field, and for the mobile field to disappear if any digi ...

Aligning multiple items to the right using Flexbox

While it's common knowledge how to align one item to the right in flexbox, what about aligning multiple items, like the last two elements, to the right and the rest to the left? Take a look at this example where I want elements with the class .r to be ...

The React button's onclick event is not displaying files from the file system as expected. Instead, no matter which link is clicked, it always shows the last file in the files object

Discovering React has been an exciting journey for me, but in this particular project, I seem to be overlooking something fundamental. If you want to check out a small sample project showcasing this issue, feel free to visit codesandbox here. Please note ...

Resolve the issue with the sticky positioning

I'm dealing with a table and struggling to make the CSS sticky position work. Can someone help me troubleshoot? .table_wrapper { width: 100%; height: 400px; overflow: auto; position: relativ ...

Issues with rendering in Next.jsORErrors encountered during rendering

Encountering errors while attempting to build my page using "Yarn Build" Automatically optimizing pages ... Error occurred prerendering page "/design/des". More details: https://err.sh/next.js/prerender-error: Error: Cannot find module './des.md&apos ...

Ways to incorporate vertical alignment while adjusting the size of a <div> block

Seeking advice on how to vertically align <div> blocks (green blocks in my example) when changing block size. What adjustments are needed in my example for the vertical alignment (middle) of side blocks to be maintained when resizing the browser win ...

Experiencing difficulties sending AJAX requests to an Express server while utilizing React Router

I am encountering difficulties with making ajax requests to fetch data from a MongoDB database. The application is coded using React, utilizing React-Router for routing and running on an Express server. The ajax calls are being handled using whatwg-fetch. ...

Is there a potential race condition in React when switching between lists?

I'm currently working on setting up a queue system where users can move items between different lists, such as from "available" to "with client". The queue's state is managed in the root React component like this: this.state = { queue: { a ...

Limit file selection to images using MUI File Input

I am currently using MUI File Input in React for a file input element. The code I have works well, but I would like to restrict this file input to only accept images. How can I achieve this? Here is what I have done so far: const [locationImg, setLoc ...

Issues with jQuery animate.css functionality specifically occurring on Firefox browser

As a beginner in jQuery, I have been exploring different animations and recently came across an issue with Firefox compatibility. I discovered the animate.css library, and decided to incorporate its animations into text captions on a slider using the Soli ...

Making a POST request to a Next.js API route results in a 500 Internal Server Error being sent back

Check out the code in createComment.ts file, which serves as a Next.js api route: import type { NextApiRequest, NextApiResponse } from 'next' import sanityClient from "@sanity/client" const config = { dataset: process.env.NEXT_PUBLI ...

hover causing the table cell to act erratically

My table consists of three cells with widths of 30%, 40%, and 30% respectively. The table itself occupies 25% of its container, which can range from 1024px to 400px. The first cell contains a button labeled GALLERY. Upon hovering over the cell, the text c ...

Incorporating pre-designed elements into the bottom section of my

I'm currently facing an issue while trying to integrate a footer content from a template into my slideout footer. The problem is that the template footer is currently spanning across the entire width of the page, and I am struggling to contain it with ...

What is the most effective way to incorporate animated hyperlinks?

I've been grappling with a webpage I'm designing, featuring sentences acting as links arranged in inline-block format. My goal is to create an animated effect that resembles twinkling stars, pausing the animation on hover. It feels like I'm ...

Is it possible to include Helvetica or a similar font in my web application for shipping?

My web-app is Java/HTML based and hosted on the cloud. Users will access it using IE, Chrome or Mozilla. I would like to use Helvetica or a similar font, but they are not readily available on most systems (windows/IE/Chrome/Mozilla). Is there a way for me ...

Is there a way to conceal the parent element when the child element is hidden from view?

Wanting to remove the stars badge in the review section of a Shopify store when there are 0 reviews for the product. The goal is to have the badge appear automatically once a review is received. Here's the code snippet: HTML <div class="spr- ...