10

我有一个模板类,很简单:

.template{
  display: none;    
}

这允许我创建一个带有 html 的块,我可以使用 jQuery 克隆它并根据自己的喜好进行轻微编辑。但是,我一直分配给要克隆的同一元素的类之一设置:

.Category{
  display:table-row-group;
  //other properties not related to this problem not shown
}

这最终会覆盖模板显示属性,这违背了使其成为模板类的全部目的。

当然,我总是可以在克隆后通过 jQuery 删除模板类的同时添加 Category 类,但这并不理想,因为重点是 html 应该易于编辑,并且可以在那里而不是在其中进行更改jQuery 代码。

想法?我在想也许我可以告诉 display 覆盖其他属性或类似的东西?

谢谢!

4

6 回答 6

23

CSS 有一个非常明确的优先顺序。

如果两个选择器具有相同的优先级(根据您的两个单类选择器),那么在所有其他条件相同的情况下,CSS 代码中最后定义的那个优先级。

所以这里的简单解决方案是移动您的模板 CSS 以降低您的 CSS 代码。

如果您出于某种原因不能这样做,最好的选择是使模板选择器更具体。例如,如果您的所有模板元素都包含在 div 元素中,并且您知道这总是正确的,您可以将选择器更改为div .template. 它现在比.Category选择器更具体,因此应该优先。

最后,您始终可以选择!important. 如果可能,我尽量避免使用它,因为如果过度使用它往往会导致问题,但它存在于需要它的情况下,事实上,像这样的情况是!important我能想到的最合理的用例。

于 2013-10-29T14:47:27.440 回答
7

正是这样!important做的;将其添加到您的价值中。

于 2013-10-29T14:40:42.763 回答
2

有两种选择:

  1. 推荐:CSS中类定义的顺序真的很重要,确保你真正想要的类在另一个之后。

  2. 不推荐:不推荐!important在句末使用,因为如果你需要覆盖它会更复杂。

于 2013-10-29T14:46:00.540 回答
1

对于快速解决方案,您可以简单地使您的 css 规则更具体:

body .Category{
  display:table-row-group;
 //other properties not related to this problem not shown
}

假设您有以下代码:

<html>
<head>
  <style>
    div{background-color:#ccc} 
    #content .Category{display:block;}
    .template{display:none;}
    .otherdiv{background-color:red;}
    body .otherdiv{background-color:green;}
</style>
</head>
<body>
  <div id="content">
    <div class="template Category" >inner template div</div>
  </div>
  <div class="template">outer template div</div>
  <div class="otherdiv">outer other div</div>
</body>
</html>

inner template div显示为 bloc,但外部不会。

你的css规则更具体,它们更“自然重要”。在我的代码中,div.otherdiv将显示为绿色,因为它body .otherdiv.otherdiv

请参阅有关 css 特异性的文章http://coding.smashingmagazine.com/2007/07/27/css-specificity-things-you-should-know/

“从0开始,样式属性加1000,每个ID加100,每个属性、类或伪类加10,每个元素名称或伪元素加1。”

完全不推荐使用!important,并非所有浏览器都支持

于 2013-10-29T14:53:50.650 回答
1

将 !IMPORTANT 添加到 .Category。

.Category{
  display:table-row-group;
  //other properties not related to this problem not shown
}
于 2013-10-29T14:43:19.107 回答
0
.template.Category {
  display: none;
}

或者只是使用 !important

.template {
  display: none !important;
}
于 2013-10-29T14:43:24.203 回答