如何在 CSS 中对类进行分组 - Tailwind

发布于 2025-01-16 08:26:12 字数 2341 浏览 5 评论 0 原文

我正在尝试对类进行分组,以便代码更加清晰易读。在 Tailwind 的 文档 中,它谈到了“@apply”,这可以用于此目标,但我正在使用 CDN,因此这对我不起作用。所以我的问题是,有什么形式可以实现我正在寻找的东西吗?也许可以使用 SASS/SCSS 或 LESS?

这是我想要的一个例子:

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

大海や 2025-01-23 08:26:12

Tailwind 鼓励您使用组件。您应该使用一个允许您创建和使用组件的系统,而不是到处复制粘贴类。

由于您的问题只是 HTML + CSS,因此您实际上没有合适的工具。但如果您使用 JS、Python、PHP 等脚本语言,您可以从元素创建组件并重用它们。由于我熟悉 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>
  )
}

然后将其用作如

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

您所见,通过这种方法,您可以将巨大的修饰符列表提取到一个小组件中,您可以多次使用该组件而无需太多重复在代码中。

您可以自由选择任何能够制作组件的工具、语言、系统。这就是 Tailwind 希望您做的事情。

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

and then use it as

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

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.

煮茶煮酒煮时光 2025-01-23 08:26:12

我发现“@layer Components”+“@apply”在我的nextjs/tailwind项目中效果很好

@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;
    }
}

HTML如下

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

I found that "@layer components" + "@apply" works well 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;
    }
}

The HTML is as follows

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">
2025-01-23 08:26:12

我理解您在阅读长行 css 类并重复将它们写入某个组件时的头痛。

值得庆幸的是,TailwindCSS 有一种方法可以在单独的文件中组织组件类,因此您可以重用 css 类。方法如下:

创建名为 ma​​in.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');
      }
      /* ... */
    }

然后你可以在你的组件中使用它:

<!-- Will look like a card, but with square corners -->
<div class="card rounded-none">
  <!-- ... -->
</div>

官方文档: 链接

一篇很好的文章描述了它:链接

I understand with your headache when reading long lines of css class and repetition to write them to some component.

Gratefully TailwindCSS has a way to organise classes of components in separated file, so you can reuse your css classes. Here is the way:

Create file named 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');
      }
      /* ... */
    }

Then you can use it in your components:

<!-- Will look like a card, but with square corners -->
<div class="card rounded-none">
  <!-- ... -->
</div>

Official document: link

Good article describe about it: link

§对你不离不弃 2025-01-23 08:26:12

你有没有尝试过这样做:

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

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>
巡山小妖精 2025-01-23 08:26:12

我知道您要求使用 SASS/LESS 类型的方法,但我认为这会增加您可能不需要的额外复杂性。我认为一些简单的 JS 将是一个很好的候选解决方案。

我的做法是用类名的 JSON 对象和一个实用函数来替换 CSS 或 StyledComponents,以将它们转换为一个大字符串。

首先,实用性。将其放在共享的地方:

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

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

然后在位于index.js旁边的styles.js之类的文件中,我会:

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'
})

这就像您的CSS文件一样。是的,您必须命名变量,但您还必须以其他方式命名您的组件,这样可以减少文件乱七八糟的情况。您还可以看到 HTML 结构而不是一堆组件名称(很可能只是 div、smh)。此外,您可以在 JSON 中包含任意数量的键/值,但您认为适合在维护时进行组织以减少认知负担。

然后,HTML/JSX:

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

我喜欢这种方法的一点是,它与 CSS 工作流程非常相似,并且 JSON 对象允许您以任何您想要的方式组织类名称(理想情况下不要嵌套,否则您将需要更复杂的 classify())。使用组件,您仍然需要处理又大又长的字符串,当您应用了数十个类时,这很烦人。如果您愿意,您甚至可以在同一个文件中执行这些操作,它只是 JavaScript。

您甚至可以通过这种方式创建实用程序样式/类,并将它们与模板字符串连接起来:

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

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

I know you asked for SASS/LESS type approaches, but I think that adds additional complexity that you may not need. I think some simple JS would be a good candidate solution.

The way I've done it is to sort of replace CSS or StyledComponents with a JSON object of class names and a utility function to turn these into one big string.

First, the utility. Put this somewhere shared:

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

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

Then in a file like styles.js that's next to the index.js, I'd have:

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 is just like your CSS file. Yes, you have to name the variables, but you'd also have to name your components doing it the other way and this keeps things way less littered with files. You also get the benefit of seeing your HTML structure rather than a bunch of component names (which are more than likely just divs, smh). Also, you can have any number of key/values in your JSON, however you see fit to organize for reduced cognitive load while maintaining.

Then, the HTML/JSX:

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

The thing I like about this approach is that it's very similar to the CSS workflow and the JSON objects allow you to organize your class names in any way you want (ideally not doing it nested or you'll need a more complex classify()). Using components, you still have big long strings to mess with which is annoying when you have tens of classes applied. You can even do these in the same file if you'd like, it's just JavaScript.

You can even create utility styles/classes this way and concat them with template strings:

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

<section className={`${utilStyles.shadowPanel} ${styles.mainSection}`>
...
</section>
花辞树 2025-01-23 08:26:12

有两种方法可以对顺风类别进行分组。一个带有nodejs,另一个没有nodejs,即使用CDN。使用脚本非常简单,您只需创建一个具有多个 tailwind 类的变量并将其插入到 DOM 中即可。

您可以使用 vanilla js 对类进行分组并应用于 DOM。将脚本插入 HTML 代码末尾,如图所示。

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

There are 2 methods to group tailwind classes. One with nodejs and another without nodejs ie using CDN. Its so simple with script, you can just create a variable with multiple tailwind classes and insert that into DOM.

You can use vanilla js to group the classes and apply on the DOM. Insert the script at the end of HTML code as shown.

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

我们的影子 2025-01-23 08:26:12

正如 Jakub Kotrs 的回答所述,鼓励使用组件系统 - 或某种循环,如 items.map()

对于遇到此问题的任何人,您可以使用“直接子级”变体 *: 来避免重复(在

  • 上):
  • <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 *:px-4 *:py-6 *:md:py-0 *:hover:bg-yellow-500 *:md:hover:bg-transparent *:text-white *:duration-500">
      <li>
        <a href="#" class="text-x1 md:hover:text-yellow-300 duration-500">Home</a>
      </li>
      <li>
        <a href="#" class="text-x1 md:hover:text-yellow-300 duration-500">About Us</a>
      </li>
      <li>
        <a href="#" class="text-x1 md:hover:text-yellow-300 duration-500">Services</a>
      </li>
      <li>
        <a href="#" class="text-x1 md:hover:text-yellow-300 duration-500">Contact Us</a>
      </li>
    </ul>
    <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>
    

    请注意,在上面我已将按钮移出

      ,因此您必须确保它也没有损坏。

    As Jakub Kotrs's answer states, it's encouraged to use a component system - or some sort of loop like a items.map().

    For anyone coming across this question, you can use the "direct children" variant *: to avoid repetition (on the <li>):

    <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 *:px-4 *:py-6 *:md:py-0 *:hover:bg-yellow-500 *:md:hover:bg-transparent *:text-white *:duration-500">
      <li>
        <a href="#" class="text-x1 md:hover:text-yellow-300 duration-500">Home</a>
      </li>
      <li>
        <a href="#" class="text-x1 md:hover:text-yellow-300 duration-500">About Us</a>
      </li>
      <li>
        <a href="#" class="text-x1 md:hover:text-yellow-300 duration-500">Services</a>
      </li>
      <li>
        <a href="#" class="text-x1 md:hover:text-yellow-300 duration-500">Contact Us</a>
      </li>
    </ul>
    <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>
    

    Note that in the above I've moved the buttons out of the <ul> so you'll have to make sure that's not broken too.

    轻拂→两袖风尘 2025-01-23 08:26:12

    您应该将“group”类添加到父级,并在使用组子类之后:

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

    在此代码之后,如果您将鼠标悬停在 div 元素上,p 元素的背景颜色将更改为红色。

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

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

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

    ~没有更多了~
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文