【问题标题】:Change color of vertical menu's <li> by css通过 css 更改垂直菜单 <li> 的颜色
【发布时间】:2013-06-13 15:15:53
【问题描述】:

我想将在&lt;ul&gt;&lt;li&gt; 中创建的垂直菜单的颜色更改为按其顺序着色。我不想给每个&lt;li&gt; 一个类来让背景变得丰富多彩。但我需要 css 来计算它 - 例如第 n 个。

假设我在&lt;li&gt; 中有 10 个菜单项:

<ul>
<li>menu 1</li>
<li>menu 2</li>
<li>menu 3</li>
<li>menu 4</li>
<li>menu 5</li>
<li>menu 6</li>
<li>menu 7</li>
<li>menu 8</li>
<li>menu 9</li>
<li>menu 10</li>
</ul>

然后我需要使用css来改变每个元素的背景颜色和悬停状态。所以我应用了css:

ul li:nth-child(1) {  
  background-color: #ccc;
}

我被困在这里。我不知道如何使每个&lt;li&gt; 成为指定的背景颜色。请你们提出一个绝妙的解决方案。

问候,

【问题讨论】:

  • 目前还不清楚您到底想要达到什么目的。请根据您的示例代码给出具体的预期结果。

标签: css colors background html-lists css-selectors


【解决方案1】:

在 CSS 中,'color' 是指字体颜色。你想使用背景颜色。所以你的 CSS 看起来像

ul li:nth-child(1) {  
  background-color: #ccc;
}
ul li:nth-child(2) {
  background-color: rgb(60,100,60);
}
etc....

如果你想用交替的颜色条纹,你可以这样做

ul li:nth-child(odd) {  
  background-color: #ccc;
}
ul li:nth-child(even) {
  background-color: rgb(60,100,60);
}

【讨论】:

  • faludi,你的解决方案很有趣。通过你的方法,我也可以通过这样做使其成为悬停状态:li:nth-child(1):hover{background-color:red} ???
  • faludi,您的解决方案有效!谢谢您的帮助。案件结案!
【解决方案2】:

我建议你为颜色设置类,比如

.green {
 background-color:green;
}

.red {
 background-color:red;
}

这样你就可以简单地将类分配给你的每个列表元素

<li class="green"></li>

另外一个好处是您无需为网页上的所有 ul 元素设置样式。

【讨论】:

    【解决方案3】:

    正如@faludi 所提到的,您可以引用以1 开头的每个li - nth-child(1) 等等。或者你可以只使用oddeven

    对于悬停颜色,您可以执行以下操作...

    ul li:hover {
      background-color: #bbbfff;  
    }
    

    jsfiddle demo

    【讨论】:

      【解决方案4】:
      ul li:nth-child(1) {  
        background-color: #ccc;
      }
      ul li:nth-child(1):hover {  
        background-color: #ddd;
      }
      ul li:nth-child(2) {
        background-color: rgb(60,100,60);
      }
      ul li:nth-child(2):hover {
        background-color: rgb(60,100,100);
      }
      

      来自faludi的解决方案,检测垂直菜单的li元素并按其顺序改变背景。

      【讨论】:

        猜你喜欢
        • 2011-07-06
        • 1970-01-01
        • 1970-01-01
        • 2015-04-13
        • 2013-05-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-08
        相关资源
        最近更新 更多