在CSS中使用类的正确方法是什么?

时间:2017-11-14 22:26:40

标签: html css code-organization

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



.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>
&#13;
&#13;
&#13;

但是,我也看到人们按属性创建类,例如在Bootstrap中:

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

.content-wrapper {
  color: blue;
}

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

2 个答案:

答案 0 :(得分:1)

如果您有一组要为其应用某些样式的元素,则创建一个类,如果您有一个要为其应用样式的元素,则创建一个ID。我相信这是最常用且通常被认为是使用CSS的最佳系统。

答案 1 :(得分:1)

如果您的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>
相关问题