简化CSS代码

时间:2010-02-15 13:38:03

标签: css

如何简化此代码?

#user_panel .subscribe, 
#user_panel .faves, 
#user_panel .tags,
#user_panel .title,
#user_panel .calendar a,
#user_panel .item .content
{
    color:#fc0;
}

我不想一直写#user_panel。有什么方法吗?

4 个答案:

答案 0 :(得分:6)

LESS(少CSS)怎么样?让你的生活变得更加轻松!

#user_panel {
   .subscribe, .faves, .tags, .title, .calendar a, .item .content {
      color:#fc0;
   }
}

编辑:根据评论,LESS仅在您使用Ruby时才有用。这是完全错误的。 LESS 用Ruby编写(不要与仅与兼容)混淆,并附带一个命令行工具less2css来转换*.less个文件到*.css个文件。

答案 1 :(得分:4)

我会选择最常见的答案,因为你没有给我一个理由不: - )

#user_panel
{
   color:#fc0;
}

另一种方法是在每个元素上添加一个额外的类,然后在需要时引用多个类,例如:

.highlight 
{
  color:#fc0;
}

<div id="user_panel">
  <span class="subscribe highlight"></span>  
  <span class="tags highlight"></span>
</div>

答案 2 :(得分:2)

你可以给每个元素一个名为.user-panel-control的第二个类,并将CSS更改为:

#user_panel .user-panel-control
{ 
    color:#fc0; 
} 

HTML看起来像这样:

<div id="user_panel">
  <span class='subscribe user-panel-control'>This is a user panel control</span>
</div>

答案 3 :(得分:1)

这就像你要得到的一样短。您可以重命名user_panel,但应尽量保持标识符的描述性,以便更轻松地维护代码。显而易见的问题是,你的选择器甚至需要#user_panel部分吗?

你可以做到:

#user_panel *{ color: #fc0 }

或者像Jon在下面那样。