1

我有以下代码,

<div id="nav">
   <a href="#" >Tab1</a>
   <a href="#" >Tab2</a>
   <a href="#" >Tab3</a>
   <a href="#" >Tab4</a>
   <a href="#" >Tab5</a>
   <a href="#" >Tab6</a>
   <a href="#" >Tab7</a>
   <a href="#" class="tab8Class">Tab8</a>
   <a href="#" >Tab9</a>
</div>

#nav a {
float: left;
color: #004761;
font-size: 12px;
font-weight: bold;
text-decoration: none;
padding: 9px 5px 9px 13px;
background-colour: white;
}

.tab8Class {
float: left;
color: #004761;
font-size: 12px;
font-weight: bold;
text-decoration: none;
padding: 9px 5px 9px 13px;
background-color: lightgray;
}

我想background-colour为 Tab8 应用不同的选项。因此,仅对于 Tab8,我在a href标签中添加了一个额外的类。

但是,即使对于 Tab8,#nav a也将覆盖tab8Class.

我怎样才能tab8Class申请?

4

7 回答 7

5

您需要使第二个规则更具体(有关更多信息,请查看MDN on Specificity),因此它不会被第一个规则覆盖。此外,您不必重复所有未更改的属性:

#nav a {
   float: left;
   color: #004761;
   font-size: 12px;
   font-weight: bold;
   text-decoration: none;
   padding: 9px 5px 9px 13px;
   background-color: white;
}

#nav .tab8Class {
   background-color: lightgray;
}

示例小提琴

There was a typo in the first rule as well: It said background-colour instead of background-color.

于 2013-03-08T11:02:00.980 回答
3

Make your selector even more specific:

#nav .tab8Class

You also remove the u in colour to have correct css:

background-color: white;
              ^
于 2013-03-08T11:02:36.783 回答
2

Use

#nav .tab8Class {

instead of:

.tab8Class {

This will make your selector more specific.

You can read about CSS specificity here.

于 2013-03-08T11:02:01.603 回答
1

只需更改 bg 颜色规则,无需重新编写所有规则。

#nav a.tab8Class{

    background: #000 ; // change the color 

}

您需要阅读有关此内容的特殊性。

于 2013-03-08T11:01:34.333 回答
1

You have 2 options:

1) remove the class and use:

#nav a:nth-child(8){
    background-color: lightgray;
}

2) this is more backward compatible:

#nav .tab8Class{
    background-color: lightgray;
}

If you want to add a special hover effect (as assted in comments)

#nav .tab8Class:hover{
     //Do something
}
于 2013-03-08T11:02:42.723 回答
1

Change your code like below

#nav a.tab8Class {
    float: left;
    color: #004761;
    font-size: 12px;
    font-weight: bold;
    text-decoration: none;
    padding: 9px 5px 9px 13px;
    background-color: lightgray;
}
于 2013-03-08T11:03:25.930 回答
-2

You can simply do it with jquery. Please add jquery library.

$(document).ready(function(){
    $('#nav a:eq(7)').addClass('tab8Class');
});
于 2013-03-08T11:05:10.047 回答