如何使用css为li中的每个span元素添加颜色

时间:2017-06-22 10:45:19

标签: html css css3 frontend

您好我在尝试使用伪为span元素添加不同的颜色。你能帮帮我吗

<ol class="hidden-xs">
  <li class="active dt-nav"><span class="dot-nav">1</span></li>
  <li class="dt-nav"><span class="dot-nav">2</span></li>
  <li class="dt-nav"><span class="dot-nav">3</span></li>
  <li class="dt-nav"><span class="dot-nav">4</span></li>
</ol>

6 个答案:

答案 0 :(得分:3)

.dt-nav:nth-child(1) {
  color:red;
}
.dt-nav:nth-child(2) {
  color:blue;
}
.dt-nav:nth-child(3) {
  color:green;
}
.dt-nav:nth-child(4) {
  color:orange;
}

答案 1 :(得分:1)

使用:nth-​​child()

li span:nth-child(1) {
  color: green;
}
li span:nth-child(2) {
  color: red;
}
li span:nth-child(3) {
  color: blue;
}

等等

答案 2 :(得分:0)

您必须为css元素选择正确的li cholds。例如:

ol.hidden-xs > li:first-child > span.dot-nav {
    color: #000000;
}

ol.hidden-xs > li:nth-child(2) > span.dot-nav {
    color: #333333;
}

ol.hidden-xs > li:nth-child(3) > span.dot-nav {
    color: #db0036;
}

ol.hidden-xs > li:last-child > span.dot-nav {
    color: #cccccc;
}

答案 3 :(得分:0)

你必须修复你的CSS并使用proper selectors

&#13;
&#13;
ol > li.dt-nav:nth-child(1) > .dot-nav {
    background: red;
}

ol > li.dt-nav:nth-child(2) > .dot-nav {
    background: black;
}

ol > li.dt-nav:nth-child(3) > .dot-nav {
    background: red;
}

ol > li.dt-nav:nth-child(4) > .dot-nav {
    background: black;
}
&#13;
<ol class="hidden-xs">
  <li class="active dt-nav"><span class="dot-nav">1</span></li>
  <li class="dt-nav"><span class="dot-nav">2</span></li>
  <li class="dt-nav"><span class="dot-nav">3</span></li>
  <li class="dt-nav"><span class="dot-nav">4</span></li>
</ol>
&#13;
&#13;
&#13;

此外,您的html格式不正确(</i>)。

答案 4 :(得分:0)

您可以尝试&#34; nth-of-type&#34;对于每个li项目,像这样:

li:nth-of-type(1) span { color: red; }
li:nth-of-type(2) span { color: white; }
li:nth-of-type(3) span { color: blue; }
li:nth-of-type(4) span { color: rebeccapurple; }

答案 5 :(得分:0)

您可以使用Sass执行以下操作:

$colors: orange, blue, red, green;

li {
  @for $i from 1 to 5 {

    &:nth-child(#{$i}) {
      span {
        $color: nth($colors, $i);
        color: $color;
      }
    }
  } 
}

https://jsfiddle.net/o6w613y3/1/