Skip to content

CSS命名空间前缀的思考 #9

@switer

Description

@switer
Owner

在使用组件化开发系统时,解决组件样式冲突使用了CSS规则添加命名空间的方式,而添加命名空间的方式有两种 层级前缀类名前缀 ,下面分析下:

命名前缀

使用类名前缀
示范样例:

<div component="header" class="header">
    <div class="header-title">title</div>
    <div class="header-home">home</div>
</div>
.header-title {color:blue;}
.header-home {height:25px; width:50px;}

命名前缀能很好地避开组件间的样式影响,划分了独立的组件样式独立空间,但缺点在于:

  1. 对于类名较长,HTML编码时添加了额外的成本
  2. 类名与命名空间耦合,组件更小粒度的拆分、代码片段复制、命名空间名称需要重新变更所有类名

层级前缀

使用父级前缀方式如下:
示范样例:

<div component="header" class="header">
    <div class="title">title</div>
    <div class="home">home</div>
</div>
.header .title {color:blue;}
.header .home {height:25px; width:50px;}

相比较,使用层级前缀的好处在于:

  1. 元素命名独立,不耦合命名空间,方便编码
  2. 由于不耦合命名空间名称,当命名空间需要变更时,只需要修改顶层元素的类名
  3. HTML Inspect,元素定位容易,不容易混淆组件与组件元素
  4. 避免了子元素与子组件的命名冲突

层级前缀方案也不是完美的,该方案的致命缺点是不能完美解决组件样式独立性的问题,问题案例如下:

<div component="index" class="index">
    <div class="title">首页</div>
    <div component="header" class="header">
        <div class="title">title</div>
        <div class="home">home</div>
    </div>
</div>

父组件index有类名为title的元素,子组件header也有类名为title的元素,所以父组件对title元素的样式描述
会层叠在header组件的title元素上。

Activity

changed the title [-]CSS命名空间前缀的思考[/-] [+]CSS命名空间前缀的思考//TBD[/+] on May 5, 2014
changed the title [-]CSS命名空间前缀的思考//TBD[/-] [+]CSS命名空间前缀的思考[/+] on May 10, 2014
NdYAG

NdYAG commented on Feb 9, 2015

@NdYAG

层级前缀的缺点可以用 .header > .title 这样的方式来解决,不过一旦写了 > 等选择器就比较依赖于 HTML 结构。
我还是更喜欢命名前缀,只要类名起得好可以避免它的缺点。

switer

switer commented on Feb 9, 2015

@switer
OwnerAuthor

@NdYAG 使用子代是不得已而为之(为了解决父-子组件的样式冲突),很多时候我只会在第一级的时候使用子代选择器:
qq 20150209202251

switer

switer commented on Feb 9, 2015

@switer
OwnerAuthor

@NdYAG Sorry,我的文章没有涉及到子代选择器。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @switer@NdYAG

        Issue actions

          CSS命名空间前缀的思考 · Issue #9 · switer/switer.github.io