📿 脊柱命名法(Kebab Case)完全介绍

脊柱命名法(Kebab Case)是一种全部小写,使用连字符 - 作为单词分隔符的命名方式。因连字符像”烤肉串”的竹签,或脊椎的骨头节而得名。

别名:kebab-case、spinal-case、dash-case、lisp-case、slug-case、HTTP case


一、核心规则

基本规则:

  1. 全部字母必须小写
  2. 单词之间使用连字符 -(ASCII 45,即减号)
  3. 不能使用下划线或大写字母
  4. 不能以连字符开头或结尾
  5. 不能包含空格或特殊字符(除非 URL 编码)

严格规则:

✅ user-profile
✅ get-user-by-id
✅ api-v2
✅ background-color
✅ my-css-class

❌ user_profile        (下划线)
❌ userProfile         (驼峰)
❌ User-Profile        (大写)
❌ -user-profile       (开头连字符)
❌ user-profile-       (结尾连字符)
❌ user name           (空格)
❌ user@profile        (特殊字符)

二、命名来源与历史

别名 来源
Kebab Case 像中东烤肉串(kebab),食材(单词)串在竹签(连字符)上
Spinal Case 像脊椎骨,一节一节由连字符连接
Lisp Case 源自 Lisp 语言的传统命名风格(如 my-variable
Dash Case 简单直接,因为使用 dash(连字符)
Slug Case URL 的 slug 部分(/my-page-title)常用

三、详细示例

✅ 正确示例全集

单单词(无需连字符)

user
profile
index
about

双单词

user-profile
get-data
api-version
background-color
font-size
margin-top

多单词

get-user-by-id
create-new-account
send-email-notification
user-profile-settings
password-reset-token

带数字

api-v2
config-v1-2
data-2024
user-123-profile

复杂场景

user-address-line-1
http-request-handler
css-class-name-with-long-description

❌ 错误示例及原因

user_profile      // ❌ 下划线(蛇形)
userProfile       // ❌ 驼峰
UserProfile       // ❌ 大驼峰
user-Profile      // ❌ 部分大写
-user-profile     // ❌ 以连字符开头
user-profile-     // ❌ 以连字符结尾
user name         // ❌ 空格
user@profile      // ❌ 特殊字符
user--profile     // ❌ 多个连续连字符(虽然某些场景允许,但不推荐)

四、主要应用场景

1. 🌐 URL 路径(最重要)

脊柱命名是 URL 路径的绝对标准

用途 示例
网站路径 https://example.com/user-profile
REST API https://api.github.com/repos/user/repo
文章链接 https://blog.com/2024/01/getting-started-with-python
产品页面 https://shop.com/products/leather-jacket

为什么 URL 必须用脊柱命名?

  • SEO 最佳:搜索引擎把 - 当空格,_ 不当空格
  • 可读性最高user-profileuser_profile 更清晰(下划线可能被链接下划线覆盖)
  • 标准惯例:RFC 3986 推荐,所有主流网站都使用
  • 避免歧义:下划线在某些字体中难以看清

2. 🎨 CSS/SCSS 类名与 ID

CSS 规范强烈推荐使用脊柱命名。

/* ✅ 推荐 */
.user-profile { }
.btn-primary { }
.card-header { }
.navbar-dark { }
.background-color-red { }

/* ❌ 不推荐(虽然能工作) */
.user_profile { }      /* 蛇形 */
.userProfile { }       /* 驼峰 */

实际案例:

<!-- HTML 中使用脊柱命名 -->
<div class="user-profile">
    <h2 class="profile-title">用户名</h2>
    <button class="btn-primary">提交</button>
    <div class="card-content">内容</div>
</div>
/* CSS 选择器(与 HTML 对应) */
.user-profile { }
.profile-title { }
.btn-primary { }
.card-content { }

3. 📦 NPM 包名

NPM(Node.js 包管理器)强制要求使用脊柱命名(除了作用域包)。

// ✅ 正确
"name": "lodash"
"name": "express"
"name": "my-awesome-package"
"name": "@my-company/ui-components"  // 作用域包可用 /,但名称部分仍用脊柱

// ❌ 错误(发布时会报错或警告)
"name": "my_awesome_package"   // 下划线
"name": "myAwesomePackage"     // 驼峰

4. 📝 Git 分支名(部分团队规范)

许多团队规定 Git 分支名使用脊柱命名。

# ✅ 常见模式
feature/user-authentication
bugfix/fix-login-error
release/v2-0-0
hotfix/security-patch

# ⚠️ 也常见(蛇形或驼峰也有)
feature_user_auth   # 有些团队用蛇形
featureUserAuth     # 有些用驼峰

# ❌ 避免
feature/User Auth   # 空格

5. 🏷️ HTML 自定义属性

<!-- ✅ HTML 自定义属性推荐 -->
<div data-user-id="123" data-product-name="laptop"></div>

<script>
// 在 JavaScript 中访问
const userId = div.dataset.userId;      // 自动转换为驼峰
const productName = div.dataset.productName;
</script>

6. 🔗 锚点链接(Markdown/HTML)

<!-- Markdown 标题自动生成的锚点 -->
## 用户配置文件
<!-- 锚点为 #用户配置文件(中文)或 #user-configuration -->

<!-- 手动指定 -->
<h2 id="user-profile-settings">设置</h2>

7. 📁 文件名(某些场景)

虽然 Python 不能用,但在某些前端项目中可见。

# ✅ 前端组件文件夹(某些框架)
my-component/
    index.js
    style.css

# ❌ Python 不能用(导致 import 错误)
my-utils.py   # import my-utils ❌ 语法错误

五、与其他命名法对比

特性 脊柱命名 (kebab) 蛇形命名 (snake) 小驼峰 (camel)
分隔符 连字符 - 下划线 _ 大写字母
大小写 全小写 全小写 首字母小写
示例 user-profile user_profile userProfile
可读性 ⭐⭐⭐⭐⭐ ⭐⭐⭐⭐⭐ ⭐⭐⭐⭐
打字速度 中等(需按 Shift + 连字符) 慢(需按 Shift + 下划线)
SEO ✅ 最佳 ❌ 差(不被分词) ❌ 差
URL 使用 必须 ⚠️ 仅查询参数 ❌ 从不
CSS 使用 推荐 ⚠️ 少见 ⚠️ 少见
Python 使用 ❌ 不可用(无法 import) 必须 ❌ 不可用
JavaScript 使用 ❌ 变量名不可用 ⚠️ 常量可用 变量/函数
NPM 包名 必须 ❌ 不可用 ❌ 不可用

六、常见问题与避坑

Q1: 为什么 Python 不能用脊柱命名?

A: 因为连字符 - 在 Python 中是减法运算符

# ❌ 假设文件名 my-utils.py
import my-utils  # 语法错误!Python 解析为 my - utils

# ✅ 必须用蛇形
import my_utils  # 正确

Q2: URL 查询参数可以用脊柱吗?

A: 可以但不常见,更推荐蛇形。

# ✅ 更常见(蛇形)
https://api.com/users?user_id=123

# ⚠️ 可以但少见(脊柱)
https://api.com/users?user-id=123

# ❌ 不要用(驼峰)
https://api.com/users?userId=123

Q3: 数字如何处理?

A: 数字可以直接放在单词前、后或中间。

# 都可以
api-v2
api-version-2
v2-api
data-2024-01-01

Q4: 连续多个连字符可以吗?

A: 不推荐。虽然有些系统不会报错,但会造成歧义。

❌ user--profile     # 不要用
❌ user---profile    # 更不要用
✅ user-profile      # 正确

Q5: 大写字母在脊柱命名中?

A: 绝对不要。脊柱命名强制全小写。

❌ User-Profile
❌ user-Profile
✅ user-profile

七、实际应用案例

案例 1:完整网站 URL 结构

https://example.com/
├── products/
│   ├── leather-jacket
│   ├── cotton-shirt
│   └── wool-scarf
├── blog/
│   ├── 2024/01/15/
│   │   └── getting-started-with-web-development
│   └── 2024/02/01/
│       └── why-kebab-case-is-best-for-urls
└── user/
    └── profile-settings

案例 2:CSS 框架(如 Bootstrap)

/* Bootstrap 类名示例 */
.btn-primary
.btn-secondary
.card-title
.card-body
.navbar-expand-lg
.modal-dialog-centered

案例 3:REST API 设计

# ✅ 推荐
GET /api/v1/user-profiles
POST /api/v1/order-items
GET /api/v1/products?category-id=5&sort-by=price

# ❌ 不推荐
GET /api/v1/userProfiles
GET /api/v1/user_profiles

案例 4:Git 分支管理策略

# 功能分支
feature/user-authentication
feature/payment-gateway
feature/shopping-cart

# 修复分支
bugfix/login-error
bugfix/checkout-crash

# 发布分支
release/v2-0-0
release/v1-5-3

# 热修复
hotfix/security-vulnerability
hotfix/critical-bug

八、转换工具与代码示例

其他命名转脊柱命名

// JavaScript 转换函数
function toKebabCase(str) {
    return str
        .match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
        .map(x => x.toLowerCase())
        .join('-');
}

console.log(toKebabCase('userProfile'));     // user-profile
console.log(toKebabCase('user_profile'));    // user-profile
console.log(toKebabCase('UserProfile'));     // user-profile
console.log(toKebabCase('HTTPRequest'));     // http-request

Python 转换(虽然不能用,但可转换字符串)

import re

def to_kebab_case(text: str) -> str:
    """将各种命名转为脊柱命名"""
    # 先统一替换分隔符为空格
    text = re.sub(r'[-_]', ' ', text)
    # 处理驼峰
    text = re.sub(r'(?<!^)(?=[A-Z])', ' ', text)
    # 转小写并用连字符连接
    return '-'.join(text.lower().split())

print(to_kebab_case('userProfile'))     # user-profile
print(to_kebab_case('user_profile'))    # user-profile
print(to_kebab_case('UserProfile'))     # user-profile

九、记忆口诀

  • 脊柱法,用小写连字符,串单词
  • URL 用它最标准CSS 用它最推荐
  • 不可大写下划线不能开头或结尾
  • Python 千万别用import 会出错

十、总结表

维度 内容
核心标识 全小写 + 连字符 -
主要场景 URL、CSS、NPM、Git 分支、HTML 属性
优点 SEO 友好、可读性最高、Web 标准
缺点 Python 不可用、打字稍慢
不要用于 Python 文件名/变量、JavaScript 变量名
常见别名 kebab-case、spinal-case、dash-case、lisp-case
标准规范 RFC 3986 (URI)、W3C (CSS)

一句话记住:URL 和 CSS 必须用脊柱命名,其他地方看语言规范!

文档更新时间: 2026-06-07 02:31   作者:月影工作室
IT运维支持-AIWALY-月影工作室