2012-10-29 107 views
0
<html> 
<head> 
    <style> 
     input[type='text'], select { 
      background: blue 
     } 

     .error { 
      background: red 
     } 
    </style> 
</head> 
<body> 
<input type="text" class="error"/> 
<select class="error"> 
    <option>non-sense</option> 
</select> 
</body> 
</html> 

如果类.error背景红色比它必须是红色。即使input[type="text"]有蓝色背景。在IE和GC进行测试。CSS选择的标签高于类

回答

2

使用.error { background: red !important }

要知道这有局限性的,请参阅:!important rules (CSS 2.1 Section 6.4.2)

+3

使用'!important'如此轻率地将你的代码从长远来看,一个真正的头痛。谨防! –

+1

'!important'?真? –

+0

@MadaraUchiha所以不会在单独的文件中搅动你的CSS。我试图解决他的问题,而不是学习他如何正确编码他的整个网站 – Caelea

5

的理由让你所看到的问题是,input[type=text].error更具体的,所以它会覆盖它。使用更具体的选择:

input.error 

或者,如果你想真正安全:

input[type=text].error 

更多有关CSS specificity, and how it's calculated


另一种方法是保持当前选择器,但在规则上添加!important关键字:

.error { background: red !important; } 

这会立即使其覆盖与元素匹配的任何其他规则。请注意,这是一个非常强大的工具,可能会在未来导致意想不到的结果。

+0

那么现在基于我的回答你提高了你自己?坏! – Caelea

+0

如果他在任何数量的标签上使用'.error',或者使用未知标签? – kontur

+0

您可以通过引用CSS特性来改进答案,以便OP可以获得有关此上下文中“更具体”的一些线索。 – eis

0

试试这个

<html> 
    <head> 
     <style> 

      input[type='text'], select { background: blue } 
      .error { background: red; } 
      input.error { background: red; } 

     </style> 
    </head> 
    <body> 
     <input type="text" class="error" /> 
     <select class="error"> 
      <option>non-sense</option> 
     </select> 
    </body> 
</html> 
+0

工作。但不用说:css是一个噩梦,如果你不知道它的每一个它不是一个错误它的一个特征功能D: – ortreum