我的 css className 命名习惯(基于bem)

发布时间:

为什么要有好的命名习惯:

通常我们开发一个组件,最外层的 className 常用的命名有 box、wrap、container

但这些通用的名字有个缺点,那就是, 在一个大项目里会有很多组件, 如果每个组件外层都用这个 className , 就会带来很大的麻烦:

1、在 IDE 里,当我们要从对应的 className 跳转到对应的代码的时候,就 会出现很多的干扰

比如这里,我想从css,跳转到 对应的ts文件,就出现了很多的干扰项

ide跳转

2、在浏览器的开发者工具里,当我们要查看对应的 className 的样式的时候,也会出现很多的干扰

名字都是 box,我根本不知道哪个div对应那个组件

浏览器的开发者工具里查看className

所以,就需要一个好的命名习惯,来避免这些问题

命名习惯

在经过研究后,我发现bem命名规范非常不错,于是我就在它的基础上,演化出了我自己的命名规则:

举例:

组件 UserProfile:

举例的组件 UserProfile

对组件进行分析后,我的命名习惯如下:

UserProfile拆分

最外层是模块名字, 子模块的命名规则是 是 外层模块__子模块, 如:

UserProfile 里的 face 模块,css命名就是 UserProfile__face

UserProfile 里的 name 模块,css命名就是 UserProfile__name


依次类推。不同模块之间用2个下划线分割,用下划线是为了方便ide来回跳转,

因为我是写react,如果用了减号分割,<div className={styles.a-box}> 是没法直接来回跳转的

最外层,我们不用 box、wrap、container, 而是使用了组件的名字:UserProfile

这种驼峰命名虽然会浪费几秒的时间来切换大小写字母,但好在这种浪费是一次性的

所以,最终,我这个组件的ts、css文件如下:

import React from 'react' import styles from 'UserProfile.module.scss' const UserProfile = () => { return ( <div className={styles.UserProfile}> <div className={styles.UserProfile__face}> <img src="/face.jpg" alt="" /> </div> <div> <div className={styles.UserProfile__name}>糊涂</div> <div className={styles.UserProfile__url}>shifenhutu.cn</div> <div className={styles.UserProfile__info}>大家好,我是糊涂</div> </div> </div> ) } export default UserProfile
.UserProfile { .UserProfile__face { } .UserProfile__name { } .UserProfile__url { } .UserProfile__info { } }

此外

对于一些内部有多个相同结构子组件的组件,如 tab,swiper,nav,命名习惯如下:

组件名_item

.tab{ .tab__item{} } .swiper{ .swiper__item{} } .nav{ .nav__item{} }

以上,就是我目前根据 bem+ 自己浅薄的经验总结出来的方案, 希望未来有更好的方案

推荐阅读:

如何看待 CSS 中 BEM 的命名方式? - 知乎 (zhihu.com) 

⒛ [规范] CSS BEM 书写规范 · Tencent/tmt-workflow Wiki (github.com) 


2025 © 糊涂.