Home > Enterprise >  How to group clases in CSS - Tailwind
How to group clases in CSS - Tailwind

Time:03-23

I am trying to group clases so the code will be cleaner and legible. In the documentation of Tailwind it talks about "@apply", that can be used for this objective but I am using the CDN and therefore this is not working for me. So my question is, ¿Is there any form I can accomplish what I am looking for? Maybe by using SASS/SCSS or LESS?

Here is an example of what I wnat:

<ul >
  <li >
    <a href="#" >Home</a>
  </li>
  <li >
    <a href="#" >About Us</a>
  </li>
  <li >
    <a href="#" >Services</a>
  </li>
  <li >
    <a href="#" >Contact Us</a>
  </li>
  <button >
    Log In
  </button>
  <button >
    Sign In
  </button>
</ul>

<ul >
  <li >
    <a href="#" >Home</a>
  </li>
  <li >
    <a href="#" >About Us</a>
  </li>
  <li >
    <a href="#" >Services</a>
  </li>
  <li >
    <a href="#" >Contact Us</a>
  </li>
  <button >
    Log In
  </button>
  <button >
    Sign In
  </button>
</ul>

CodePudding user response:

Tailwind encourages you to use components. Instead of copy pasting the classes all over the place, you should use a system that allows you to create and use components.

Since your question is HTML CSS only, you don't really have the right tools for this. But if you were using a scripting language like JS, Python, PHP etc., you could create components from elements and reuse them. Since I am familiar with React framework, I can show an example of that:

function NavElement(props) {
  return (
    <li >
      <a href={props.href} >{props.children}</a>
    </li>
  )
}

and then use it as

function NavElements() {
  return (
    <ul >
      <NavElement href="/">Home</NavElement>
      <NavElement href="/services">Services</NavElement>
      <NavElement href="/about-us">About us</NavElement>
    </ul>
  )
}

As you can see, with this approach, you extract the huge list of modifiers into a small component that you can use multiple times without much repetition in the code.

You are free to choose any tool, language, system that will enable making components. That is what Tailwind kind of expects you to do.

CodePudding user response:

have you tried doing:

<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>

CodePudding user response:

You should add 'group' class to parent and after work with group subclasses:

<div >
  <p >lorem ipsum</p>
</div>

after this code if you hover on div element, p elements backgroundColor will be change to red.

  • Related