search
HomeWeb Front-endCSS TutorialHow to write elegant and durable css code? Sharing css naming tips!

If you've been working with CSS for a while, you know that inheritance, specificity, and naming are some of the hardest things to deal with. Since all CSS is global, as your codebase grows, it becomes increasingly difficult to prevent styles from conflicting with each other and causing unintended side effects! The following article will share with you some CSS naming tips to make our code elegant and attractive. I hope it will be helpful to everyone!

How to write elegant and durable css code? Sharing css naming tips!

CSS Naming——BEM

What is BEM

BEM is a CSS naming convention. [Recommended learning: css video tutorial]

BEM stands for "block, element, modifier".

In the selector, the following three symbols represent extended relationships:

-   中划线 :仅作为连字符使用,表示某个块或者某个子元素的多单词之间的连接记号。
__  双下划线:双下划线用来连接块和块的子元素
_   单下划线:单下划线用来描述一个块或者块的子元素的一种状态

Use BEM example comparison

Block

As in the example below, li.item is a sub-element of the list

/* 常规写法和BEM写法相同 */
.list

Element

/* 常规写法 */ 
  
        
  • Pricing
  •     
  • Contact
  •   
   /* BEM写法 */       
        
  • Pricing
  •     
  • Contact
  •   
/* 常规写法 */ 
.list{} 
.list .item{} 

/* BEM写法 */ 
.list{} 
.list__item{}

Modifier

A "modifier" can be understood as a specific state of a block!

/* 常规写法 */ 
  
        
  • Pricing
  •     
  • Contact
  •   
   /* BEM写法 */      
        
  •       Pricing     
  •     
  • Contact
  •   
rrree

Benefits of BEM

    ##Get rid of the trouble of specificity
  • Fix inheritance problems
  • stop worrying about naming

Several principles of css naming

##Short names are better than long names Because short naming shortens writing time, it also reduces the size of css files! For example, this example:

/* 常规写法 */ 
.list{} 
.list .item{} 
.list .item.active{} 

/* BEM写法 */ 
.list{} 
.list__item{}
.list__item_active{}

Combined naming is better than single naming

//  推荐
.some-intro{...}

// 不推荐
.some-introduction{...}

Attribute-oriented naming and Semantic namingAttribute-oriented naming means that the naming of the selector follows the specific CSS style and has nothing to do with the project, page, or module. For example, the more classic clear floating class name.clearfix:

// 不建议
.header{...}

//推荐
.cs-header{...}

The semantic-oriented naming is named according to the context in which the application element is located. For example:

.clearfix:after { content : ''; display: table; clear: both; }

The above two naming methods have their own advantages and disadvantages:

1. Attribute-oriented

    Advantages
  • : Reuse of CSS High efficiency, best performance, plug and play, convenient and fast, and development is also extremely fast because it saves a lot of time switching between HTML and CSS files.
  • Disadvantages
  • : Due to its single attribute, its applicable scenarios are limited. In addition, because it is easy to use, it is easily overused, resulting in higher maintenance costs.
  • 2. Semantics-oriented

    Advantages
  • It has a wide range of application scenarios, can achieve very exquisite layout effects, and is easy to expand;
  • Disadvantages
  • : The code is long and the development efficiency is average, because all HTML needs to be named, even if it is a 10-pixel spacing. This leads many developers to either choose to use the tag selector directly, or to choose a simple class name and then define the style through the parent-child relationship, which results in worse maintenance problems.
Name summary recommendation

Status

.header { background-color: #333; color: #fff; }
.logo {font-size: 0; color : transparent;}

Layout

前一个    prev
后一个    next
当前的    current

显示的    show
隐藏的    hide
打开的    open
关闭的    close

选中的    selected
有效的    active
默认的    default
反转的    toggle

禁用的    disabled
危险的    danger
主要的    primary
成功的    success
提醒的    info
警告的    warning
出错的    error

大型的    lg
小型的    sm
超小的    xs

Common Parts

文档    doc
头部    header(hd)
主体    body    
尾部    footer(ft)    
主栏    main
侧栏    side    
容器    box/container

Component

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

Semantic widget

按钮        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

Functional widget

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

Recommended naming websitecodelf: https://unbug.github.io/codelf

Reference document:

1. "CSS Selection World" by Zhang Xinxu

2. https://www.cnblogs.com/qianxiaox/p/13816077.html

(Learning video sharing:

webfrontend

)

The above is the detailed content of How to write elegant and durable css code? Sharing css naming tips!. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
Creating a Reusable Pagination Component in VueCreating a Reusable Pagination Component in VueApr 22, 2025 am 11:17 AM

The idea behind most of web applications is to fetch data from the database and present it to the user in the best possible way. When we deal with data there

Using 'box shadows' and clip-path togetherUsing 'box shadows' and clip-path togetherApr 22, 2025 am 11:13 AM

Let's do a little step-by-step of a situation where you can't quite do what seems to make sense, but you can still get it done with CSS trickery. In this

All About mailto: LinksAll About mailto: LinksApr 22, 2025 am 11:04 AM

You can make a garden variety anchor link () open up a new email. Let's take a little journey into this feature. It's pretty easy to use, but as with anything

It's pretty cool how Netlify CMS works with any flat file site generatorIt's pretty cool how Netlify CMS works with any flat file site generatorApr 22, 2025 am 11:03 AM

Little confession here: when I first saw Netlify CMS at a glance, I thought: cool, maybe I'll try that someday when I'm exploring CMSs for a new project. Then

Testing for Visual Regressions with PercyTesting for Visual Regressions with PercyApr 22, 2025 am 11:02 AM

It’s a Herculean task to test

Edge Goes Chromium: What Does it Mean for Front-End Developers?Edge Goes Chromium: What Does it Mean for Front-End Developers?Apr 22, 2025 am 10:58 AM

In December 2018, Microsoft announced that Edge would adopt Chromium, the open source project that powers Google Chrome. Many within the industry reacted with

A Gutenburg-Powered NewsletterA Gutenburg-Powered NewsletterApr 22, 2025 am 10:57 AM

I like Gutenberg, the new WordPress editor. I'm not oblivious to all the conversation around accessibility, UX, and readiness, but I know how hard it is to

Using  for Menus and Dialogs is an Interesting IdeaUsing for Menus and Dialogs is an Interesting IdeaApr 22, 2025 am 10:56 AM

Using for a menu may be an interesting idea, but perhaps not something to actually ship in production. See "More Details on "

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 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor