5

例如,哪个更好:

方法1(分别命名类):

/* CSS */

.textbox-red, 
.textbox-green {
   padding: 10px;
   border: 1px solid #CCC;
   border-radius: 10px;   
}

.textbox-red { color: #900; }
.textbox-green { color: #3c3; }

/*HTML*/

<div class="textbox-red"></div>
<div class="textbox-green"></div>

或者 - - - - - -

方法2(链类):

/* CSS */

.textbox {
  padding: 10px;
  border: 1px solid #CCC;
  border-radius: 10px;
}

.textbox.text-red { color: #900; }
.textbox.text-green { color: #3c3; }

/*HTML*/

<div class="textbox text-red"></div>
<div class="textbox text-green"></div>

两者之间有什么更好的做法?

4

4 回答 4

5

我的意见是你应该使用模块化 CSS - 你也可以组合类而不是链接它们:

/*CSS*/
.textbox {
  padding: 10px;
  border: 1px solid #CCC;
  border-radius: 10px;
}

.text-red { color: #900; }
.text-green { color: #3c3; }

/*HTML*/

<div class="textbox text-red"></div>
<div class="textbox text-green"></div>

这样,当您想要没有文本框的红色背景时,您可以重复使用红色和绿色。这样,您可以更多地重用您的代码,并且您的文本框和文本颜色之间存在松散耦合

于 2013-02-08T09:52:00.030 回答
1

我个人会使用方法 2。这样,您可以轻松地将 text-red 或 text-green 换成 text-blue 或 text-yellow,并且仍然保留文本的基本样式。基本上,方法 2 允许更大的灵活性和可维护性,恕我直言。

于 2013-02-08T09:55:54.053 回答
0

根据我的经验,模块化方法为您提供了最大的灵活性。模块化 css 模式也用于Twitter Bootstrap,其中灵活性非常重要。

于 2013-02-08T09:49:24.953 回答
-2

首先,如果您为 IE6 制作样式,则更好,因为此浏览器不支持第二种方法。

于 2013-02-08T09:46:57.123 回答