Ways to categorize CSS classes using Tailwind

Trying to organize classes for cleaner and more readable code. The Tailwind documentation mentions the use of "@apply" for this purpose, but as I am using the CDN, this is not working for me. So my question is, Is there a way I can achieve what I want? Perhaps by using SASS/SCSS or LESS?

Here is an example of what I am looking for:

<ul class="md:flex md:items-center z-[-1] md:z-auto md:static absolute bg-gray-800 w-full left-0 md:w-auto md:py-0 py-4 md:pr-0 pr-7 md:pl-0 pl-7 md:opacity-100 opacity-0 top-[-400px] transition-all ease-in duration-200">
  <li class="nav-element">
    <a href="#" class="text-x1 md:hover:text-yellow-300 duration-500">Home</a>
  </li>
  <li class="px-4 py-6 md:py-0 hover:bg-yellow-500 md:hover:bg-transparent text-white duration-500">
    <a href="#" class="text-x1 md:hover:text-yellow-300 duration-500">About Us</a>
  </li>
  <li class="px-4 py-6 md:py-0 hover:bg-yellow-500 md:hover:bg-transparent text-white duration-500">
    <a href="#" class="text-x1 md:hover:text-yellow-300 duration-500">Services</a>
  </li>
  <li class="px-4 py-6 md:py-0 hover:bg-yellow-500 md:hover:bg-transparent text-white duration-500">
    <a href="#" class="text-x1 md:hover:text-yellow-300 duration-500">Contact Us</a>
  </li>
  <button class="md:w-auto w-full bg-transparent text-white font-[Poppins] duration-500 px-6 py-2 hover:bg-white hover:text-gray-800 border border-white border-dotted rounded-lg">
    Log In
  </button>
  <button class="md:w-auto w-full bg-yellow-500 text-white font-[Poppins] duration-500 px-6 py-2 md:mx-4 hover:bg-yellow-600 rounded-lg">
    Sign In
  </button>
</ul>

<ul class="nav-elemnts">
  <li class="nav-element">
    <a href="#" class="nav-link">Home</a>
  </li>
  <li class="nav-element">
    <a href="#" class="nav-link">About Us</a>
  </li>
  <li class="nav-element">
    <a href="#" class="nav-link">Services</a>
  </li>
  <li class="nav-element">
    <a href="#" class="nav-link">Contact Us</a>
  </li>
  <button class="button-login">
    Log In
  </button>
  <button class="button-signin">
    Sign In
  </button>
</ul>

Answer №1

Embrace the use of components in Tailwind. Instead of scattering classes everywhere, opt for a system that facilitates component creation and reuse.

Without the ability to use scripting languages like JS, Python, PHP, etc., creating components may be challenging. However, I can demonstrate how this can be done using React:

function NavElement(props) {
  return (
    <li class="px-4 py-6 md:py-0 hover:bg-yellow-500 md:hover:bg-transparent text-white duration-500">
      <a href={props.href} class="text-x1 md:hover:text-yellow-300 duration-500">{props.children}</a>
    </li>
  )
}

Utilize this component as follows:

function NavElements() {
  return (
    <ul class="md:flex md:items-center z-[-1] md:z-auto md:static absolute bg-gray-800 w-full left-0 md:w-auto md:py-0 py-4 md:pr-0 pr-7 md:pl-0 pl-7 md:opacity-100 opacity-0 top-[-400px] transition-all ease-in duration-200">
      <NavElement href="/">Home</NavElement>
      <NavElement href="/services">Services</NavElement>
      <NavElement href="/about-us">About us</NavElement>
    </ul>
  )
}

This approach allows you to condense a long list of modifiers into a reusable component, reducing code repetition significantly.

Choose any tool or language that facilitates component creation; this is the essence of what Tailwind encourages.

Answer №2

I've discovered that using "@layer components" along with "@apply" is very effective in my nextjs/tailwind project

@tailwind base;
@tailwind components;
@tailwind utilities;

@layer components {
    .login-page {
        @apply bg-gray-50 dark:bg-gray-900;      
    }
    .login-container {
        @apply flex flex-col items-center justify-center px-6 py-8 mx-auto;
    }
    .login-title {
        @apply flex items-center mb-6 text-2xl font-semibold;
    }
    .login-card {
        @apply w-full bg-white rounded-lg shadow dark:border md:mt-0;
    }
}

Here is the corresponding HTML code

export default function Login() {
return (
    <section className="login-page">
        <div className="login-container">
            <a href="#" className="login-title">
                SineWave Engineering
            </a>
            <div className="login-card">
                <div className="p-6 space-y-4 md:space-y-6 sm:p-8">

Answer №3

Dealing with long lines of repetitive CSS classes can be a headache, especially when trying to apply them to multiple components.

Fortunately, TailwindCSS offers a solution for organizing component classes in separate files to easily reuse them. Here's how:

Begin by creating a file called main.css

@tailwind base;
@tailwind components;
@tailwind utilities;

@layer components {
  .card {
    background-color: theme('colors.white');
    border-radius: theme('borderRadius.lg');
    padding: theme('spacing.6');
    box-shadow: theme('boxShadow.xl');
  }
  /* ... */
}

Once your file is set up, you can use it in your components like this:

<!-- This div will resemble a card, but with square corners -->
<div class="card rounded-none">
  <!-- ... -->
</div>

For more information, check out the official document here

There's also a great article explaining the process in detail here

Answer №4

Did you attempt this:

<style type="text/tailwindcss">
    @layer components {
      .some-class {
        @apply px-4 py-6 md:py-0 hover:bg-yellow-500 md:hover:bg-transparent text-white duration-500;
      }
    }
</style>

Answer №5

While you requested SASS/LESS type approaches, I believe that may introduce unnecessary complexity. A simple JS solution could suffice.

My approach involves replacing CSS or StyledComponents with a JSON object of class names and a utility function to combine them into a single string.

First, the utility function should be placed in a shared location:

// turns a JSON object's values into a single string (keys are irrelevant)

export const classify = (classes) => Object.values(classes).join(' ')

Next, create a file like styles.js adjacent to index.js with the following content:

import { classify } from 'shared/utils'

export const nav = classify({
  base: 'absolute bg-gray-800 w-full left-0 pr-7 pl-7 py-4 opacity-0 top-[-400px] z-[-1]',
  animation: 'transition-all ease-in duration-200',
  larger: 'md:flex md:items-center md:z-auto md:static md:w-auto md:py-0  md:pr-0 md:pl-0 md:opacity-100'
})

export const navItem = classify({
  base: 'px-4 py-6 hover:bg-yellow-500 text-white',
  resp: 'md:py-0 md:hover:bg-transparent',
  anim: 'duration-500'
})

This approach mimics a CSS file structure. While variables need to be named, it helps to cut down on file clutter. Additionally, it provides a clearer HTML structure compared to component names. The JSON objects allow for flexible organization and reduced cognitive load.

For the HTML/JSX part:

import * as styles from './styles'

export default Component = (props) => (
  <ul className={styles.nav}>
    <li className={styles.navItem}> ... </li>
    <li className={styles.navItem}> ... </li>
    <li className={styles.navItem}> ... </li>
  </ul>
)

This approach closely resembles the CSS workflow, enabling easy class organization within JSON objects. It eliminates the need to deal with long strings of classes when applying them to components. Additionally, utility styles can be created and combined using template strings.

For example:

import * as utilStyles from 'utils/styles'
import * as styles from './styles'

<section className={`${utilStyles.shadowPanel} ${styles.mainSection}`>
...
</section>

Answer №6

Two ways to group tailwind classes: one with nodejs and the other without nodejs using CDN. It's easy with a script - create a variable with multiple tailwind classes and insert it into the DOM.

You can group the classes with vanilla js and apply them to the DOM. Add the script at the end of the HTML code as shown below.

<body>
<ul class="nav-elemnts">
  <li class="nav-element">
    <a href="#" class="nav-link">Home</a>
  </li>
  <li class="nav-element">
    <a href="#" class="nav-link">About Us</a>
  </li>
  <li class="nav-element">
    <a href="#" class="nav-link">Services</a>
  </li>
  <li class="nav-element">
    <a href="#" class="nav-link">Contact Us</a>
  </li>
  <button class="button-login">
    Log In
  </button>
  <button class="button-signin">
    Sign In
  </button>
</ul>
<script>
let nav-link="text-x1 md:hover:text-yellow-300 duration-500"
Array.from(document.getElementsByClassName("nav-link")).forEach((el)=>el.className=nav-link)
</script>
</body>

Answer №7

Consider applying the 'group' class to the parent element and then manipulating the group subclasses:

<div class="group p-4">
  <p class="group-hover:bg-red-400">lorem ipsum</p>
</div>

Upon hovering over the div element, the background color of the p elements will change to red.

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

Select only eBook files using this HTML form: {file-type}

I am looking to implement a form that includes an option to upload files by selecting "choose file". However, I want to restrict the displayed files to only show .epub and .mobi files when the user opens the selection pop-up box on their operating system. ...

jQuery .html() function malfunctioning

I am just starting out with front-end development and have taken on the challenge of creating a simple Tic Tac Toe game using HTML5. To set up the game board, I decided to use a table element in my code. Below is the snippet of HTML that I have implemented ...

The application of Tailwind style does not appear to be working within the Material-ui Drawer component in NextJs

How can I incorporate Tailwind styling within a @mui/material/drawer component? import { Close } from "@mui/icons-material"; import { Box, Drawer, IconButton, TextField } from "@mui/material"; import { useContext} from "react" ...

Turn off automatic resizing of iframes

I'm currently dealing with a webpage that contains an iframe. The iframe contains quite a bit of data, and every time it loads, its height adjusts to match the content within. Unfortunately, this is causing my page layout to be disrupted. Is there a w ...

Retrieving text snippet from an HTML document using .NET

Users input HTML content using a richtext editor, allowing for a variety of elements. Here is an example of such content: <h1>Header 1</h1> <p>Some text here</p><p>Some more text here</p> <div align=right><a hr ...

A method to extract the value of an array by referencing the primary key value

To create a unique name for my extra text field, I am utilizing the primary key of the room_extras table. For example: <tr> <td><?php echo $extrasInfo['description'] ?></td> <td> <input type="tex ...

Loading animation reminiscent of a whirlpool, similar to the movement

In my quest for the perfect animation, I have scoured far and wide. Unfortunately, the one I found at http://jsfiddle.net/pedox/yed68/embedded/result/ is created using css, which many browsers do not yet support fully. I also explored , but found it to be ...

Navigate to the adjacent IDs

I have multiple sections with varying content and links (previous and next) to navigate to the next section. Initially, everything functions properly. However, when adding a new section in between existing ones, I am required to update all the ids to ensu ...

Having trouble aligning the unordered list with the input

Can anyone help me troubleshoot my CSS so that the list appears below the input field? Check out this example The nested menu in this example is positioned too far to the left and slightly too high. It should be aligned with the bottom of the containing ...

Creating diagonal ribbon designs can add a unique and dynamic touch to any

Can anyone help me figure out how to create a ribbon similar to the image below using CSS? I have managed to make the slanted filled box with text inside, but I am having trouble with the flaps. Check out this CodePen link for reference. ...

The comparison between dynamically adding elements through Javascript and hiding them using CSS

I am contemplating the advantages and disadvantages of adding elements to a page and setting display:none versus creating a function that dynamically generates the elements and appends them where needed. In my current situation, I am implementing a reply ...

Unable to apply .png image using the content property in a Symfony project

I have a png image located in src/AppBundle/Resources/public/img To set the png image using the css content property, I used this code: content: url(../../public/assets/img/optional-checked.png); However, I encountered an error: GET http://127.0.0.1:80 ...

Python Selenium for Element Detection

I am a beginner when it comes to using Selenium and I am currently seeking guidance on how to locate the element that is highlighted in this image: https://i.sstatic.net/uXf4u.png Despite my attempts, the following code resulted in an error message being ...

Filtering Tables with AngularJS

Currently, I'm experimenting with using angularJS to filter data in a table. My goal is to load the data from a JSON file that has a structure like this (example file): [{name: "Moroni", age: 50}, {name: "Tiancum", age: 43}, { ...

Experiencing difficulties with setting the width of owl carousel

Here is the HTML code snippet: <div class="row"> <div class="col-lg-7 col-sm-6"> <div class="owl-carousel" id="homeCarousel"> <div class="item"> <img src="images/brela.jpg" alt="brela makarska"> </d ...

Incorporating Only XSD Files into an HTML Input Tag: A Simple Guide

Is there a way to restrict a file input element to only display XSD files? I attempted the following: <input type="file" accept="text/xsd" > Unfortunately, this method is not working as it still allows all file formats to be disp ...

Eliminate any height changes in the ul element during a CSS transition

Here is the code I've been using to style my side navigation, which has been working perfectly without any transitions. SCSS Code and a functional JSFiddle .side-nav{ position: fixed; z-index: 100; right: 0; margin-top: 15vh; ul { lis ...

Solve woff file imports using Rollup

I am currently working on bundling a theme package using Rollup.js. The theme contains some global styles, specifically @font-face. I am importing the fonts and planning to inject them using styled-components injectGlobal. However, I am encountering an is ...

PHP multiple file uploads can allow users to upload and

Can anyone help me with a problem I'm facing? I built a file uploader that works fine until I try to save the uploaded file name in a database. When I attempt to do so, I receive this error message: Warning: mysql_real_escape_string() expects para ...

The mdb navigation bar seems to constantly change its height

Having an issue with the height of my mdb navbar in my Angular app. It randomly flips to a larger size when reloading the page, but returns to normal when I open the developer console in Chrome. Two screenshots show the correct display and the incorrect i ...