【问题标题】:What is the correct way to use classes in CSS?在 CSS 中使用类的正确方法是什么?
【发布时间】:2018-04-28 00:30:36
【问题描述】:

我看到人们为每个对象创建类,例如:

.content-wrapper {
  display: flex;    
  justify-content: center;    
  color: white;    
}

.images-wrapper {
  display: flex;    
  justify-content: center;
  border: 1px solid white;
}
<div class="content-wrapper"></div>
<div class="images-wrapper"></div>

而且,我看到人们通过属性创建类,例如在 Bootstrap 中:

.centered-content {
  display: flex;
  justify-content: center;
}

.content-wrapper {
  color: blue;
}

.images-wrapper {
  border: 2px solid black;
}
<div class="centered-content content-wrapper"></div>
<div class="centered-content images-wrapper"></div>

【问题讨论】:

  • 第一个应该是ID,而不是类。
  • 这确实是一个开放性问题,可以辩论,有些人提出了命名约定/解决方案,例如 BEM、SMACSS,我认为这是一个很好的讲座getbem.com/introduction
  • @NiettheDarkAbsol ID 的唯一问题是你可能会因为特殊性问题而让你的生活更加困难。
  • 任何类的命名都不应与它所分类的内容无关。由于您不提供任何内容,因此任何类命名策略都无效。

标签: html css code-organization


【解决方案1】:

如果您希望为一组元素应用某种样式,请创建一个类,如果您希望为一个元素应用某种样式,请创建一个 ID。我相信这是使用 CSS 的最常见且普遍认为最好的系统。

【讨论】:

    【解决方案2】:

    当您的 html 中有重复的样式时,您可能需要为所有使用该样式的 DOM 创建一个类。

    例如

    <style>
       .box1{
             width: 300px;
             background-color: blue;
       }
       .subbox2{
             width: 30px;
             background-color: green;
       }
      .center{
             margin: auto;
             position: absolute;
      }
    </style>
    
    <div class="center box1">
      <div class= "center subbox2"></div>
    </div>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-04
      • 2011-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多