关于使用原子类css的优缺点

观点来自于以下文章

https://juejin.cn/post/7161211941652791304
https://zhuanlan.zhihu.com/p/425134873

优点

唯一性,更改会更安全

命名唯一,无重复,修改时是修改类,不是修改类的样式,不会影响其他地方

复用性强,项目大小增长曲线趋缓

这样相比似乎只是把css的大小转移到了html,最终可能只是少了几个字节。但是可以推断,当用的越多的时候,少的就越多,所以我说趋缓

<-- 原子类 -->
<template>
  <div class="flex items-center">
    <div class="flex items-center"></div>
  </div>
</template>
<style>
.flex {
  display: flex;
}
.items-center {
  align-items: center;
}
</style>
<-- BEM写法 -->
<template>
  <div class="card">
    <div class="card-body"></div>
  </div>
</template>
<style lang="scss">
.card {
  display: flex;
  align-items: center;
  &-body {
    display: flex;
    align-items: center;
  }
}
</style>

降低命名负担

可以减少/不再为思考class命名而烦恼

减少嵌套命名(冗长的类)

不用遵循BEM的嵌套命名方式

便捷的响应式、暗黑模式、悬停/聚焦等状态

treeshaking(taiwindcss V3、windicss、unocss)

不用维护删除废弃的样式,随意使用,只会构建使用到的类

开发时不用html和css来回切换

提高开发效率

缺点

刚开始接触的记忆负担

影响开发效率,解决方案安装对应的vscode插件,语法提示能够帮助我们,但是仍然无法完全避免去翻官方文档

蓝湖的代码无法直接复制使用

解决方案,开发一个js脚本,识别代码并转换成类名

复杂样式类名太多难以阅读和维护

<button
  class="blue-400 hover:blue-500 dark:blue-500 dark:hover:blue-600 text-sm text-white font-mono font-light py-2 px-4 border-2 rounded border-blue-200"
>
  Button
</button>

解决方案

<!-- 1、Attributify模式  tailwindcss目前不支持,而且复杂的样式还是会冗长难读 -->
<button
  bg="blue-400 hover:blue-500 dark:blue-500 dark:hover:blue-600"
  text="sm white"
  font="mono light"
  p="y-2 x-4"
  border="2 rounded blue-200"
>
  Button
</button>
<template>
  <button :class="[btn, btnDark]"></button>
</template>
<script setup>
  // 2、变量提取  为了提高维护性,按某个标准去划分变量,缺点:分类和变量命名负担、js和html来回切换
  const btn = 'blue-400 hover:blue-500 text-sm text-white font-mono font-light py-2 px-4 border-2 rounded border-blue-200'
  const btnDark = 'dark:blue-500 dark:hover:blue-600'
</script>
<template>
  <button class="btn-primary"></button>
</template>
<style>
  // 3、apply提取  这个提取的类是能够达到复用,但缺点是其中所引用的类并没有,等同于原本的css代码,不建议
  .btn-primary {
    @apply blue-400 hover:blue-500 dark:blue-500 dark:hover:blue-600 text-sm text-white font-mono font-light py-2 px-4 border-2 rounded border-blue-200;
  }
</style>

以上三个方案其实都无法彻底解决问题,只能算优化。

综上,我个人觉得,对于简单样式的项目比如后台,用起来真的很香。另外在设计有规范标准的情况下,做好分层和组件提取是可以大大降低这个缺点带来的影响(参考开篇引用文章中提到 ITCSS 架构)。否则,非样式简单的项目只用一些常用且意思明确的类,然后注意不要用的太多导致冗长,结合css代码一起使用,原子类只是作为协助。不然考虑到项目的维护性,还是不用为宜~

最后,其实我自己有个疑问,这种原子类,对渲染性能是提高了还是降低了,直觉上我认为是提高的,毕竟全部类都是一层,没有了类的嵌套,但碍于找不到直接的规范/标准支撑观点

© 版权声明
THE END
喜欢就支持一下吧
点赞8 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容