What? ? ? CSS can be atomized too! | JD Cloud Technical Team

1.What is atomized CSS?

Atomic CSS is the approach to CSS architecture that favors small, single-purpose classes with names based on visual function. Let’s Define Exactly What Atomic CSS is 

The translation of the above meaning is that atomized CSS is a CSS architecture method that tends to use single-purpose and simple CSS. Classes are usually named based on visual effects. Different from BEM-ruled CSS, atomic means to CSS is split, and each style has a unique CSS rule. The example is as follows. Each style is configured with a fixed class name:

// margin为0px
.m-0{
    margin:0px;
}
// 文字为红色
.text-red{
    color:red;
}
.font-blod{
  font-weight:blod;
}
.text-center{
   text-align:center;
}

// 样式使用方式
 <div class = "m-10 text-center text-red font-bold font-size-[48px]">你好原子化CSS</div>

The style effect is as follows:

There are currently many atomic frameworks, such as Tailwind CSS , Windi CSS , and Tachyons .

2. Why atomicize CSS?

The traditional method may be to use, for example, a scss preprocessor to generate the class you want, as shown below:

@for $i from 1 through 10 {
  .m-#{$i} {
    margin: $i px;
  }
}
// 结果为:
.m-1 { margin: 1 px; } 
.m-2 { margin: 2 px; } 
/* ... */ 
.m-10 { margin: 10 px; }

The above method will generate classes that can be used in many scenarios, which can cover many scenarios, but many of them will not be used, resulting in a lot of redundancy; therefore, this is also optimized in atomized CSS. Reduce the packaging volume of CSS through presets based on the concept of on-demand loading;

Compared with the original writing method, applying atomized CSS can reduce a lot of CSS writing work and reduce the repetitive code added each time a new style is added. For example, the flex and margin configurations in a project are generally written many times, using atomic CSS There is no need to re-write these styles with CSS. Directly binding the corresponding class name can achieve the same effect, thus reducing the overall number of lines of code and useless workload in the project;

At the style writing level, CSS pre-processing and post-processing rely heavily on separate style sheets. Atomized CSS can make full use of Sass and Less. Wait for the CSS preprocessor function to write styles, and you can use PostCSS to further enhance the functionality of CSS. As for inline styles, although it is technically supported to use preprocessing and postprocessing to process them, there are few mature tools to provide support and maintenance for this.
At the consistency level, atomic CSS frameworks generally have a predefined design system, and developers can only choose the values ​​to set in the design system. For inline styles or traditional CSS class definitions, there are no restrictions on the values ​​that can be set. For inline styles or traditional CSS class settings, the font size of a label may be 14px or 0.875rem, when the product (or customer) When it is said that it needs to be adjusted smaller, developer A may adjust it to 13px, and developer B may adjust it to 12px. But for the atomic CSS framework, turning it down means changing the class setting from text-sm to text-xs.

In general, atomized CSS can reduce the size of CSS, improve the reuse rate of CSS classes, and reduce the complexity of class naming; however, due to the accumulation of multiple CSS styles, it may cause the disadvantage of too long class names; at the same time, it increases Remember the memory cost of CSS styles;

So who is using atomic CSS today?

Some websites have begun to use atomic CSS such as github , swiper.js , etc.↓As shown in the figure below, the CSS type of their pages can clearly see that they use atomic CSS.





3. An atomized CSS framework-UnoCss

UnoCSS is an engine, not a framework, because it does not provide core tool classes, and all functions can be provided through presets and inline configuration;

Similar to Vite 's on-demand loading concept, unocss provides packaging and usage methods, which greatly reduces memory and improves running speed. It also provides plug-in presets for enhancement, and custom rules can be used for rule verification . Increase the way of personalized development.

UnoCSS official website link

The specific usage is as follows:

1. Set up the environment

Make sure the node version of your project is >=16

pnpm add -D @unocss/preset-uno

2. Modify configuration

2.1 Modify vite.config.js

As shown in the code below, Unocss is introduced

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import viteCompression from 'vite-plugin-compression'
import UnoCSS from 'unocss/vite'
export default defineConfig(({command, mode})=>({
 plugins: [
  vue(),
  viteCompression(),
  UnoCSS({configFile: '../uno.config'}) 
 ]
 })  // 引入下文配置好的config文件

2.2Create uno.config.js

import {
    defineConfig,
    presetAttributify,
    presetIcons,
    presetTypography,
    presetUno,
    presetWebFonts,
    transformerDirectives,
    transformerVariantGroup
  } from 'unocss'
import presetUno from '@unocss/preset-uno'
export default defineConfig({
   rules: [
        [/^mg-0.([\.\d]+)$/, ([_, num]) => ({ margin: `(${num}px)` })],
    ],
    shortcuts: [
      // ...
    ],
    theme: {
      colors: {
        // ...
      }
    },
    presets: [
      presetUno(),
      presetAttributify(),
      presetTypography(),
      presetWebFonts({
        fonts: {
          // ...
        }
      })// 使用自带的内部预设,按需引用
    ] 
    transformers: [transformerDirectives(), transformerVariantGroup()] })

3.UnoCSS multiple functions:

3.1 Custom style rules:

You can customize the rules in config.js. For example, mb-300px is official. You can write mg-10 below because I customized the regular rules in the config file, which represents: margin: 10px;

The rule configuration code is as follows:

 rules: [ [/^mg-0.([\.\d]+)$/, ([_, num]) => ({ margin: `(${num}px)` })], ],

3.2 Icons:

<!-- A basic anchor icon from Phosphor icons -->
<div class="i-ph-anchor-simple-thin" />
<!-- An orange alarm from Material Design Icons -->
<div class="i-mdi-alarm text-orange-400" />
<!-- A large Vue logo -->
<div class="i-logos-vue text-3xl" />
<!-- Sun in light mode, Moon in dark mode, from Carbon -->
<button class="i-carbon-sun dark:i-carbon-moon" />
<!-- Twemoji of laugh, turns to tear on hovering -->
<div class="i-twemoji-grinning-face-with-smiling-eyes hover:i-twemoji-face-with-tears-of-joy" />

The display effect is as follows. When the mouse is moved, rotation and other animations will be performed:

3.3 Attribute mode:

Compared with the normal mode, it is more readable and maintainable; compared with the two modes, the attribute mode style is more intuitive and more readable;

//使用属性模式和普通模式进行对比:
// 普通模式:
<div class="bg-blue-400 hover:bg-blue-500 text-sm text-white py-2 px-4 border-2 rounded border-blue-200">普通模式 </div>
//属性模式
<div 
  bg="blue-400 hover:blue-500"
  text="sm white"
  font="mono light"
  p="y-2 x-4"
  border="2 rounded  blue-200"
>
  属性模式
</div>

The effect is as follows:

At the same time, after installing the UnoCSS plug-in in vscode, there will be prompts when writing code. When placed on the css style, specific CSS styles will appear to make development easier~ As shown in the figure below, code prompts will be provided during the process of writing class names, which is very friendly. ;





4. Personal feelings

In the process of using UnoCSS, I feel the joy of not having to write <style></style>, and there is no need to intersperse CSS files and VUE files back and forth. The CSS class name can be written casually, and any style you want can be piled up without having to go through it. racking your brains to think of class names brings a lot of convenience; however, there are also certain difficulties, that is, it will cause confusion in being unable to quickly locate style problems;

All in all, there are still many places worth exploring in UnoCSS. Here are only some of the places that I think are interesting. There are always many bugs in open source projects waiting for us to solve. Let’s discuss them together~

 

Author: Jingdong Insurance Zhuo Yaqian

Source: JD Cloud Developer Community Please indicate the source when reprinting

Qt 6.6 is officially released. The pop-up window on the lottery page of Gome App insults its founder . Ubuntu 23.10 is officially released. You might as well take advantage of Friday to upgrade! RISC-V: not controlled by any single company or country. Ubuntu 23.10 release episode: ISO image was urgently "recalled" due to containing hate speech. Russian companies produce computers and servers based on Loongson processors. ChromeOS is a Linux distribution using Google Desktop Environment 23-year - old PhD student fixes 22-year-old "ghost bug" in Firefox TiDB 7.4 released: officially compatible with MySQL 8.0 Microsoft launches Windows Terminal Canary version
{{o.name}}
{{m.name}}

Guess you like

Origin my.oschina.net/u/4090830/blog/10117955