简体   繁体   English

CSS无法与HTML标签一起正常使用

[英]CSS doesn't work properly with HTML tag a

HTML code: HTML代码:

<div class='abc'>
    <a>test1</a>
    <a class='active'>test2</a>
</div>

CSS code: CSS代码:

.abc a { color: red; }
.active { color: green; }

Result: DEMO 结果: 演示

Question : 问题

As you can see, all tag A appear red color, class '.active' doesn't take effect, what caused this result and how to solve it? 如您所见,所有标签A都显示为红色,类'.active'无效,是什么导致此结果以及如何解决呢?

Thanks. 谢谢。

.abc a consists of a class selector and a type selector. .abc a由类选择器和类型选择器组成。

.active consists of only a class selector. .active仅包含一个类选择器。

This means .abc a is more specific . 这意味着.abc a具体 Since they both match the same element and set the same property, the more specific one wins. 因为它们都匹配相同的元素并设置了相同的属性,所以更具体的一个将获胜。

Make the rule you want to apply more specific: .abc a.active . 使您要应用的规则更具体: .abc a.active

Try: 尝试:

.abc a{color: red}
.abc .active{color:green}

The reason it's not working is because your first line of CSS is more specific than just .active and will always take priority. 它不起作用的原因是因为您的CSS第一行比.active更具体,并且总是优先考虑的。 The more specific the more priority will have. 具体程度越高,优先级越高。

“ .abc a”优先于“ .active”,您正在寻找的是:.abc .active

you will need to this 您将需要此

Js fiddle 小提琴

  .abc a{color: red}

  a.active{color:green}

Try: 尝试:

.abc a{color: red}
a.active{color:green}

To override a property... 覆盖属性...

The problem is because of specifity (like the other answers pointed out). 问题是由于特定性(如指出的其他答案)。 Another way to force this would be to add !important at the end of the style: 强制执行此操作的另一种方法是在样式的末尾添加!important:

.active { color: green !important; }

Not the most elegant solution (actually discouraged), but may work in scenarios where coding all of the specifity scenarios would involve too much work (eg changing the color of all elements with class active in response to an alert). 这不是最优雅的解决方案(实际上不建议使用),但可能适用于对所有特殊情况场景进行编码会涉及过多工作的情况(例如,在响应警报的情况下使用活动的类来更改所有元素的颜色)。 More information: http://webdesign.about.com/od/css/f/blcssfaqimportn.htm 详细信息: http : //webdesign.about.com/od/css/f/blcssfaqimportn.htm

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM