CSS奇怪甚至并排放置相同的颜色

时间:2014-03-22 21:56:53

标签: html css

我不希望相同颜色并排。目前:1-2-1-1-2但必须是:1-2-1-2-1

HTML

<ul class="list list-unstyled">
  <li>The_hangover_part_1.avi<span class="pull-right">25Gb</span></li>
  <li>The_hangover_part_1_intro.avi<span class="pull-right">15Gb</span></li>
  <li>Covers<span class="pull-right">255Kb</span></li>
  <ul>
    <li>the_hangover_part_1_cover_1.jpg<span class="pull-right">123Kb</span></li>
    <li>the_hangover_part_1_cover_2.jpg<span class="pull-right">122Kb</span></li>
    <li>the_hangover_part_1_cover_2.jpg<span class="pull-right">122Kb</span></li>
  </ul>
</ul>

CSS

.list li:nth-child(even) {
  background: transparent;
}
.list li:nth-child(odd) {
  background-color: rgba(255,255,255,0.05);
}

2 个答案:

答案 0 :(得分:1)

首先,您需要更正HTML。 ul元素不能直接嵌套在另一个ul中,它必须位于li之一:

<ul class="list list-unstyled">
  <li>The_hangover_part_1.avi<span class="pull-right">25Gb</span></li>
  <li>The_hangover_part_1_intro.avi<span class="pull-right">15Gb</span></li>
  <li>Covers<span class="pull-right">255Kb</span>
    <ul>
      <li>the_hangover_part_1_cover_1.jpg<span class="pull-right">123Kb</span></li>
      <li>the_hangover_part_1_cover_2.jpg<span class="pull-right">122Kb</span></li>
      <li>the_hangover_part_1_cover_2.jpg<span class="pull-right">122Kb</span></li>
    </ul>
  </li>
</ul>

然后,当您获得正确的标记时,您可以重新定义主列表中奇数项的子项的颜色顺序:

.list li:nth-child(odd) li:nth-child(odd) {
  background: transparent;
}
.list li:nth-child(odd) li:nth-child(even) {
  background-color: rgba(255,255,255,0.05);
}

答案 1 :(得分:0)

这是因为:nth-child选择器只查看其直接父级中的位置。要解决此问题,您可以删除li之外的ul标记,并通过为其提供包含缩进样式的类来缩进它们。