Using CSS Cascading Layers in Web Projects

WBOY
Release: 2024-07-19 17:55:00
Original
324 people have browsed it

Using CSS Cascading Layers in Web Projects

The full name of CSS is Cascading Style Sheets. An important concept of it is "cascading". Styles declared later will overwrite the previous ones. style. This feature makes it very convenient for us to make some fine-tuning while inheriting the old style when developing new content.

With the engineering of front-end development, especially the widespread use of frameworks such as Vue.js, we need to manage more and more fragmented style files in the project. When these style files are related to each other, we often need to pay more effort to make the order in which they appear in the HTML document meet our expectations.

Thankfully, we now have CSS Cascading Layers.

By cascading layers, we can categorize CSS code very conveniently, so that the styles in the layer are always logically ordered the way we want, without caring about how they appear in the HTML document order.

CSS Cascading Layers has been confirmed as Baseline 2022, you can use this feature with confidence.

ideal engineering practice

Atomic Design is a commonly used design pattern in modern web development. We can follow this design and divide the style layer into the following five layers:

  1. Atoms
  2. Molecules
  3. Organisms
  4. Templates
  5. Pages

In actual projects, you may need to increase or decrease them, such as adding a base layer to standardize the initial style in different browsers (Reboot/Normalize), so the style layer in the final project may look like this:

/* 规范基础样式、定义CSS自定义属性等 */
@layer base { /* ... */ }

/* 我们可以借助子层来排序这些可重用组件的样式 */
@layer components.atoms { /* ... */ }
@layer components.molecules { /* ... */ }
@layer components.organisms { /* ... */ }

/* 模板可以被归类到布局中 */
@layer layouts { /* ... */ }
@layer pages { /* ... */ }
Copy after login

As long as we ensure that the layers are defined in this order at the beginning of the HTML document, we can directly place the style code in the layer in subsequent development without having to worry about the order in which they are imported.



  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <!-- 在定义层时,可以用简写 -->
  <style>@layer base, components.atoms, components.molecules, components.organisms, layouts, pages;</style>
  <!-- 实际的样式代码从这里之后导入 -->
  <style>/* ... */</style>
  <link rel="stylesheet" href="...">





Copy after login

Used in conjunction with TailwindCSS

At present, most of the component libraries combined with TailwindCSS adjust the style of components through JS control tool classes. This article will not discuss this method. TailwindCSS can be combined with any component library with the help of cascading layers, allowing us to use tailwind to fine-tune the style of the component library.

TailWindCSS already has the concept of layers. In versions before version 4, simulated layers are still used, not real cascading layers. In order to make the TailwindCSS style appear in the appropriate position in our project, we Need to rewrite the import file:

/*
 * "base"这个层名会被TailwindCSS当作它的逻辑层处理,
 * 此处我们使用"tailwind-base"代替
 */
@layer tailwind-base {
  @tailwind base;
}

/*
 * "utilities"和"variants"同理,
 * 但我们无需定义两个层来包裹它们,因为它们始终应该定义在我们的样式之后
 */
@layer tailwind-utilities {
  @tailwind utilities;
  @tailwind variants;
}
Copy after login

Then, let’s adjust the definition of the cascade layer:

/*
 * 注意!我在此处删除了前文中的base层,
 * tailwind的base已经包含了样式的规范化内容,
 * 我们的工程通常不需要再次格式化
 */
@layer
  tailwind-base,
  components.atoms,
  components.molecules,
  components.organisms,
  layouts,
  pages,
  tailwind-utilities;
Copy after login

Use with component library

The component library is an essential part of the front-end project. Based on the above, we can easily think that the style of the component should be between the "base" layer (or "tailwind-base" layer) and the "layout" layer. space, that is, in the "components" layer. As for where it should be in the components, you need to decide based on the actual situation. We can use the characteristics of the sub-layer to sort

However, the vast majority of component libraries do not use the cascading layer. Directly importing the styles of the component library will cause them to appear outside all layers. Under the cascading layer rules, their styles will have the highest priority. We Their styles cannot be overridden using tailwind or other means.

To solve this problem, I developed a postcss plugin that can add cascading layers to imported styles through configuration.

Next, take the Vite project as an example to briefly explain how to use the element-plus component library in the project.

The content of initializing the project and installing TailwindCSS and Element Plus is omitted here. Regardless of whether you use automatic import to introduce Element Plus, you can follow the steps in this article.

First, install @web-baseline/postcss-wrap-up-layer, you can choose your preferred package manager:

yarn add -D @web-baseline/postcss-wrap-up-layer
Copy after login

Then, use this plugin in vite.config.ts file:

/* 这里省略了其他无关的配置内容 */

import WrapUpLayer from '@web-baseline/postcss-wrap-up-layer';

export default defineConfig({
  css: {
    postcss: {
      plugins: [
        WrapUpLayer({
          rules: [
            {
              /* 此处使用了正则进行匹配 */
              includes: /^node_modules\/element-plus\//,
              layerName: 'components.element-plus',
            },
          ],
        }),
      ],
    },
  },
})
Copy after login

That’s it, this plug-in will add a cascading layer of settings to all matched files. If you use other component libraries, you can make similar settings.

More convenient handling of CSS cascading layers in Vue SFC (Single File Component)

In Vue's single-file component, we can use to define styles, where we can directly wrap the style in a cascading layer, like this:

<template>
  <h2 class="title">Title</h2>
</template>

<style scoped>
@layer components.atoms {
  .title {
    font-size: 3rem;
  }
}
</style>
Copy after login

This is inconvenient and not pretty. Normally, we don't pay attention to which layer the style is in, and we don't want to see this always-existing indentation. Therefore, I also developed a vite plug-in that allows you to use cascading layers in the form of attributes (such as:

Install @web-baseline/vite-plugin-vue-style-layer:

yarn add -D @web-baseline/vite-plugin-vue-style-layer
Copy after login

Use this plugin in vite.config.ts file:

/* 这里省略了其他无关的配置内容 */

import Vue from '@vitejs/plugin-vue';
import VueStyleLayer from '@web-baseline/vite-plugin-vue-style-layer';

export default defineConfig({
  plugins: [
    Vue(),
    VueStyleLayer(),
  ],
})
Copy after login

In this way, the above component can be rewritten as follows:

<template>
  <h2 class="title">Title</h2>
</template>

<style scoped layer="components.atoms">
.title {
  font-size: 3rem;
}
</style>
Copy after login

我认为,这或许可以成为Vue SFC官方支持的功能,甚至是新的Web特性,将layer作为

这个Vite插件目前已经满足了使用的需要,但我知道它还有些许不足之处,我正在考虑将其使用 unplugin 重构,以支持更多的框架,而不仅仅是Vite+Vue。

在Nuxt中使用级联层

我通常使用Nuxt进行Web开发,而以上的功能在Nuxt中配置需要分散在各处,因此我将它们合并为一个模块以集中配置。由于Nuxt并不公开HTML文档的编辑,我在模块中添加了级联层排序字段。

安装@web-baseline/nuxt-css-layer:

yarn add -D @web-baseline/nuxt-css-layer
Copy after login

在nuxt.config.ts文件中使用这个模块:

/* 这里省略了其他无关的配置内容 */
export default defineNuxtConfig({
  modules: [
    '@web-baseline/nuxt-css-layer',
    '@nuxtjs/tailwindcss',
    '@element-plus/nuxt',
  ],
  cssLayer: {
    rules: [
      {
        includes: /^node_modules\/element-plus\//,
        layerName: 'components.element-plus',
      },
    ],
    cssLayerOrder: [
      'tailwind-base',
      'components.element-plus',
      'components.atoms',
      'components.molecules',
      'components.organisms',
      'layouts',
      'pages',
      'tailwind-utilities',
    ],
  },
});
Copy after login

结语

在CSS级联层的帮助下,我们可以方便的在大型项目中管理样式文件,同时也允许我们将TailwindCSS与那些传统的组件库结合使用。

感谢您的阅读,如果您觉得我的工作对您有所帮助,欢迎为我的仓库添加Star!

  • @web-baseline/postcss-wrap-up-layer
  • @web-baseline/vite-plugin-vue-style-layer
  • @web-baseline/nuxt-css-layer

如果您在使用的过程中发现任何问题,欢迎提出issue以及提出pr!

The above is the detailed content of Using CSS Cascading Layers in Web Projects. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!