search

CSS naming rules

Jul 18, 2017 pm 05:49 PM
csspractice

Previous words

Whenever writing HTML structure involves CSS naming, you have to struggle. There are many CSS naming specifications on the market, such as OOCSS, SMACSS, BEM and MVCSS. The most popular among them is probably BEM. This article will introduce CSS naming in detail

Mainstream naming

[BEM]

Speaking of CSS naming, of course BEM must be mentioned. BEM means B module (block), E element (element), and M modifier (modifier). The module and the sub-element are separated by two underscores, and the sub-element and the modifier are separated by two dashes

. Regarding the sub-element E, there are two ways to write it. One is to write according to hierarchical nesting, such as block-ele1-son-inner, but writing this way will cause the name to be too long; the other is to flatten, all sub-elements under a module B, Regardless of the mutual level, they are directly connected to B, such as block-inner, but this cannot express the hierarchical relationship, and conflicts may also occur when naming.

   BEM's naming is very good, Otherwise, it would not become the most popular naming method. However, BEM’s naming of sub-elements, whether it is hierarchical long naming or flat short naming, has flaws

[NEC]

Compared with BEM, which uses module B as the top-level element, the sub-elements The element class name contains the naming of the inheritance relationship. NetEase's NEC specification uses the descendant selector method

NEC divides elements into 5 categories: layout (grid) (.g-); module (module) (.m -); unit (.u-); function (.f-); skin (.s-); status (.z-). The descendant selector does not need to fully represent the structure tree level, and should be as short as possible

.m-list{margin:0;padding:0;}.m-list .itm{margin:1px;padding:1px;}.m-list .cnt{margin-left:100px;}

Personally, I think NetEase’s approach to element classification is very good. Some globally reusable functional modules are distinguished to make the structure clearer. However, I personally don't agree with the way descendant selectors are used. When the nesting level is deep, naming conflicts are still a problem

[JD]

JD.com’s naming rules use long names that represent hierarchical nesting relationships. When the descendant module exceeds level 4 or above, consider an identifiable independent abbreviation in the ancestor module as the new descendant module

<div>
<div></div>
<div>
<div><div>
<img  src="/static/imghwm/default1.png" data-src="" class="lazy" alt="CSS naming rules" ><!-- 这个时候 miui 为 modulename_info_user_img 首字母缩写--><div></div>
<div></div>...</div></div>
<div></div>
</div>
</div>

The name of the factor element like Jingdong is too long and The method of using acronyms is very good. So far, there is no other better solution to long naming on the market

Naming method

[Descendant selector or class name]

Regarding CSS naming, the biggest debate is whether to use descendant selectors or class names. As shown in the following example


If you use the first long class name method to set the style for the

  • element, you only need to set it as follows
    .list-item{}

    If you use the second short class name method, set the style for the

  • element, you need to set it as follows
    .list .item{}

    If you use the third descendant selection To set the style for the

  • element, you need to set it as follows
    .list li{}

    From a simple point of view, the third descendant selector method is the simplest and does not require any effort. Time to name the child elements, and it’s easy to write in sass

    .list{
        li{}
    }

      但是,它有一个很严重的问题,就是如果HTML结构层级较深,往往出现选择器层级过长,如.list li span a{}

      而且,因为后代选择器强烈地依赖HTML结构,为了避免因为少写一层结构,导致选择器特殊性降低,样式无法生效的情况,也不得不这样写

      一个不得不提的问题是,CSS选择器的解析顺序是从右到左。而使用后代选择器.list li{},浏览器需要遍历出所有的li,再找出.list下的li,效率是最低的

      因此,个人认为第三种后代选择器的方式并不是好选择

      下面介绍第二种短类名的方式

      1、选择器解析效率比第三种方式好,毕竟.item比li的范围小很多

      2、短类名.list .item同样存在依赖HTML结构的情况,很可能出现选择器层级过长

      3、使用较简易,在sass中书写容易,且起名也较简单

      4、由于给li增加了类名,于是增加了HTML文件大小

      最后介绍第三种长类名的方式

      这种方式的选择器效率最高,因为.list-item这个类型页面中只出现一次,可类比于id选择器的解析速度

      由于使用长类名的方式,可以完全不使用后代选择器,则无需考虑选择器特殊性较低,样式无法生效的情况,也不会出现选择器层级过长,因为它仅有一级

      但是,相应地,它最大的缺点是类名较长,大大地增加了HTML文件大小。于是,可借鉴京东,当子孙模块超过3级时,采用首字母缩写,并将缩写后首字母大写的做法,在如将.list-item-link-title缩写为.Lil-title

      最终,选择可缩写的长类名作为CSS命名的主要方式

    【分隔符】

      一般地,classname分隔符有3种,中划线-,下划线_,以及首字母大写,以分隔list和item为例

    //中划线
    list-item
    //下划线
    list_item
    //首字母大写
    listItem

      1、中划线

      中划线可以用来表示层级关系

    <div><ul>
    <li>
    <li>
    <li>
    </ul></div>

      2、下划线

      下划线可以用来表示不同的状态

    <div>
    <button></button><button></button>
    </div>

      3、首字母大写

      首字母大写可以用来表示因为样式的需要,而不得不增加的HTML结构。一般地,如果在外层增加结构,可以增加Wrap,在内层增加结构,可以增加Inner,且不影响原先的classname的命名

    <div>
    <section><h2></h2>
    <p></p></section>    </div>

    【组件】

      通过上面的长命名方式和分隔符的使用,解决了基础结构的命名。但是,在页面中,很可能出现一些组件的应用,这些组件可以复用到页面的多个位置。这时,再使用上面的方式就不太合适

      于是,可以以m-为前缀,来表示这是一个组件

    <div>
    <button></button><button></button>
    </div>

     

    命名推荐

      有了合适的命名方式,还需要语义化命名,且有不影响语义的情况下,可以简写

    【布局】

    <span style="color: #000000;">文档    doc
    头部    header(hd)
    主体    body    
    尾部    footer(ft)    
    主栏    main
    侧栏    side    
    容器    box/container<br></span>

    【通用部件】

    列表    list
    列表项  item
    表格    table    
    表单    form
    链接    link
    标题    caption/heading/title
    菜单    menu
    集合    group
    条      bar
    内容    content    
    结果    result

    【组件】

    按钮        button(btn)
    字体        icon
    下拉菜单     dropdown
    工具栏       toolbar
    分页         page
    缩略图       thumbnail
    警告框       alert
    进度条       progress
    导航条       navbar
    导航         nav    
    子导航       subnav
    面包屑       breadcrumb(crumb)    
    标签        label
    徽章        badge
    巨幕        jumbotron
    面板        panel
    洼地        well
    标签页      tab
    提示框      tooltip
    弹出框      popover
    轮播图      carousel
    手风琴      collapse 
    定位浮标    affix

    【语义化小部件】

    品牌        brand
    标志        logo
    额外部件    addon
    版权        copyright
    注册        regist(reg)
    登录        login
    搜索        search    
    热点        hot
    帮助        help
    信息        info
    提示        tips
    开关        toggle
    新闻        news
    广告        advertise(ad)
    排行        top    
    下载        download

    【功能部件】

    左浮动    fl
    右浮动    fr
    清浮动    clear

    【状态】

    前一个    previous
    后一个    next
    当前的    current
    
    显示的    show
    隐藏的    hide
    打开的    open
    关闭的    close
    
    选中的    selected
    有效的    active
    默认的    default
    反转的    toggle
    
    禁用的    disabled
    危险的    danger
    主要的    primary
    成功的    success
    提醒的    info
    警告的    warning
    出错的    error
    
    大型的    lg
    小型的    sm
    超小的    xs

     

    实践

    <header><nav><div>联系方式:400-888-8888</div>
    <ul>
    <li><a>登录</a></li>
    <li><a>快速注册</a></li>
    <li><a>关于</a></li>
    <li><a>帮助</a></li>
    </ul></nav>...</header>

      关于CSS命名,并没有最佳实践之说,根据项目的复杂程序进行合适的命名才是可取的  

      欢迎交流  

  • The above is the detailed content of CSS naming rules. For more information, please follow other related articles on the PHP Chinese website!

    Statement
    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
    How do you create a list in HTML?How do you create a list in HTML?May 06, 2025 am 12:01 AM

    TocreatealistinHTML,useforunorderedlistsandfororderedlists:1)Forunorderedlists,wrapitemsinanduseforeachitem,renderingasabulletedlist.2)Fororderedlists,useandfornumberedlists,customizablewiththetypeattributefordifferentnumberingstyles.

    HTML in Action: Examples of Website StructureHTML in Action: Examples of Website StructureMay 05, 2025 am 12:03 AM

    HTML is used to build websites with clear structure. 1) Use tags such as, and define the website structure. 2) Examples show the structure of blogs and e-commerce websites. 3) Avoid common mistakes such as incorrect label nesting. 4) Optimize performance by reducing HTTP requests and using semantic tags.

    How do you insert an image into an HTML page?How do you insert an image into an HTML page?May 04, 2025 am 12:02 AM

    ToinsertanimageintoanHTMLpage,usethetagwithsrcandaltattributes.1)UsealttextforaccessibilityandSEO.2)Implementsrcsetforresponsiveimages.3)Applylazyloadingwithloading="lazy"tooptimizeperformance.4)OptimizeimagesusingtoolslikeImageOptimtoreduc

    HTML's Purpose: Enabling Web Browsers to Display ContentHTML's Purpose: Enabling Web Browsers to Display ContentMay 03, 2025 am 12:03 AM

    The core purpose of HTML is to enable the browser to understand and display web content. 1. HTML defines the web page structure and content through tags, such as, to, etc. 2. HTML5 enhances multimedia support and introduces and tags. 3.HTML provides form elements to support user interaction. 4. Optimizing HTML code can improve web page performance, such as reducing HTTP requests and compressing HTML.

    Why are HTML tags important for web development?Why are HTML tags important for web development?May 02, 2025 am 12:03 AM

    HTMLtagsareessentialforwebdevelopmentastheystructureandenhancewebpages.1)Theydefinelayout,semantics,andinteractivity.2)SemantictagsimproveaccessibilityandSEO.3)Properuseoftagscanoptimizeperformanceandensurecross-browsercompatibility.

    Explain the importance of using consistent coding style for HTML tags and attributes.Explain the importance of using consistent coding style for HTML tags and attributes.May 01, 2025 am 12:01 AM

    A consistent HTML encoding style is important because it improves the readability, maintainability and efficiency of the code. 1) Use lowercase tags and attributes, 2) Keep consistent indentation, 3) Select and stick to single or double quotes, 4) Avoid mixing different styles in projects, 5) Use automation tools such as Prettier or ESLint to ensure consistency in styles.

    How to implement multi-project carousel in Bootstrap 4?How to implement multi-project carousel in Bootstrap 4?Apr 30, 2025 pm 03:24 PM

    Solution to implement multi-project carousel in Bootstrap4 Implementing multi-project carousel in Bootstrap4 is not an easy task. Although Bootstrap...

    How does deepseek official website achieve the effect of penetrating mouse scroll event?How does deepseek official website achieve the effect of penetrating mouse scroll event?Apr 30, 2025 pm 03:21 PM

    How to achieve the effect of mouse scrolling event penetration? When we browse the web, we often encounter some special interaction designs. For example, on deepseek official website, �...

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    SublimeText3 Linux new version

    SublimeText3 Linux new version

    SublimeText3 Linux latest version

    Dreamweaver Mac version

    Dreamweaver Mac version

    Visual web development tools

    WebStorm Mac version

    WebStorm Mac version

    Useful JavaScript development tools

    PhpStorm Mac version

    PhpStorm Mac version

    The latest (2018.2.1) professional PHP integrated development tool

    DVWA

    DVWA

    Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software