是否有命名类的标准方法?

Sat*_*ato 6 html css naming-conventions semantic-markup

例如:

class="profile profile-image profile-image-large"
Run Code Online (Sandbox Code Playgroud)

要么

class="profile profile-image profile-image-small"
Run Code Online (Sandbox Code Playgroud)

这些名字或破折号有什么问题吗?

Sin*_*1ty 1

老实说,这取决于各个开发人员和他们自己的感受。正如您所建议的那样,有两种同样好的构建 CSS 类的方法:

.profile.image.large{
    width: 300px;
}

/* Or: */
.profile-image-large{
    width:300px;
}
Run Code Online (Sandbox Code Playgroud)

他们实现了同样的目标,但当你开始广泛思考时,你就会发现这些风格之间的差距有多大。

分离类使它们可重用: DRY约定是永远不要重复自己。通过分离largeimage类,我们可以重用同一个类:

.blue{
    border: 3px solid blue; /* All .blue's will have a blue border */
}

.profile.blue{
    border-style: dashed; /* Inherits from the previous blue and replaces the solid with a dash. */
}
Run Code Online (Sandbox Code Playgroud)

在第二种方法中 - 使用-分隔符,代码为:

.blue{
    border: 3px solid blue; /* All .blue's will have a blue border */
}

.profile-blue{
    border: 3px dashed blue; /* We had to redefine the entire style */
}
Run Code Online (Sandbox Code Playgroud)

在像 a 这样的简单示例中border,这似乎并不重要。但请考虑到更大的 CSS 块,您可能希望在整个代码中重复使用数十次。你会经常重复自己的话。

从逻辑上讲,对样式进行分组仍然是一件好事:我并不是说这-classes是一件坏事 - 它们有助于为您的代码定义命名空间,因此从维护模块化代码的意义上来说,用标识符作为样式前缀将有助于防止冲突,尤其是如果您正在网络机构内部开发将被重用的代码,或者您正在构建插件(在这种情况下,绝对需要样式前缀)。

使用像 SCSS(我的首选环境)这样的编译语言进行开发也会改变您的思维方式。在 SASS/SCSS 中我们可以轻松做到这一点:

.profile{
    display: block;

    &-image{
        border: 1px solid blue;
    }
}
Run Code Online (Sandbox Code Playgroud)

profile profile-image其计算结果与元素相同。另外,SASS 还支持:

.profile{
    display: block;

    &.image{
        border: 1px solid blue;
    }
}
Run Code Online (Sandbox Code Playgroud)

其计算结果为profile image一个元素。非常相似 - 但两种样式都仅限于其父元素.profile,不能全局使用。样式受到保护,而在我的第一个“自然”CSS 示例中,该类可以由HTML 页面中的任何blue元素自由添加和合并。

编辑:您仍然可以在 SASS 代码中使用全局.image样式,然后覆盖各个示例,但就我个人而言,我认为这违反了 DRY 原则,并且我尽量避免这样做。

那么什么是 TL;DR?

在我看来,没有“正确答案”。从约定的角度来看,值得注意的是,像Twitter-Boostrap这样的框架使用了两种样式的混合 - 可以在任何地方应用的全局类,与保护子样式的前缀类混合。

对于任何程序员来说,最重要的是您的代码清晰可读和定义,并且您使用尽可能少的代码来实现您的结果 - 无论您使用什么方法。