Html 如何使用 CSS 为选定的列表项赋予不同的颜色?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13086375/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 03:35:36  来源:igfitidea点击:

How to give a different color to a selected list item with CSS?

htmlcss

提问by Cullen

I know this question has been asked so many times before. But I just can't find the right trick for my code. I want a different color for my active list item in the navigation bar. Obviously. Silly little thing. I know. But please try to help.

我知道这个问题之前已经被问过很多次了。但我就是找不到适合我的代码的正确技巧。我想为导航栏中的活动列表项使用不同的颜色。明显地。愚蠢的小东西。我知道。但请尝试提供帮助。

Here's my HTMLcode:

这是我的HTML代码:

<div id="container">  
    <ul id="nav">  
        <li class="active"><a href="am_home.html">Home</a></li>  
        <li><a href="am_teachingassistants.php">Teaching Assistants</a></li>  
        <li><a href="am_courseinfo.php">Course Info</a></li>  
        <li><a href="am_timetable.php">Time Table</a></li>  
    </ul>  
</div>  

and Here's the CSSfile:

这是CSS文件:

#container {
    position: relative;
    top: -2em;
    z-index: 2;
    width: 1200px;
    margin: auto auto;
}

#nav {
   position: relative;
   float: left;
   margin-left: 400px;
}

#nav li {
    list-style: none;
    float: left;
    border-right: 1px solid #afc4cc;
}

#nav li a {
   position: relative;
   z-index: 2;
   float: left;
   padding: 5px 45px;
   font-size: 15px;
   font-weight: bold;
   font-family: helvetica, arial, sans-serif;
   text-decoration: none;
   color: #39aea8;
}

ul, li {
    margin: 0;
    padding: 0;
}

ul#nav li a:link,ul#nav li a:visited {
    color: #39aea8;
    text-decoration: none;
}

ul#nav li a:hover,ul#nav li a:active {
    color: #f4ba51;
    text-decoration: none;
}

回答by Rohit Azad

There's something wrong with your CSS code. Just replace this:

您的 CSS 代码有问题。只需替换这个:

 ul#nav li a:hover,ul#nav li a:active{    
}

with this:

有了这个:

 ul#nav li a:hover,ul#nav li.active a{
 // here styling 
}

and you are good to go. You just made a mistake while calling the active class in CSS.

你很高兴去。您只是在 CSS 中调用活动类时犯了一个错误。

回答by ShibinRagh

ul#nav li.active a { color: #f4ba51 ; }