使用nth-child()选择元素

时间:2016-06-30 07:56:27

标签: html css

如何使用css li概念定位所选或活跃li之前/之前元素的nth-child()

<ul>
  <li><li>
  <li>i want to select this li</li>
  <li class="active"></li>
  <li><li>
</ul>

1 个答案:

答案 0 :(得分:2)

CSS中没有先前的兄弟选择器,但是有一个下一个相邻的兄弟选择器(使用+选择器):

li.active {
  color: red;
}
li.active + li {
  color: green;
}
<ul>
  <li></li>
  <li>This one can't be selected with pure CSS only...</li>
  <li class="active">This is the active one</li>
  <li>This is adjacent to active</li>
</ul>

编辑 - 这是一种使用prev()选择前一个兄弟姐妹的jQuery方式:

$("li.active").prev().addClass("prevsibling");
li.active {
  color: red;
}
li.prevsibling, li.active + li {
  color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
  <li></li>
  <li>This one has had a class appended via jQuery!</li>
  <li class="active">This is the active one</li>
  <li>This is adjacent to active</li>
</ul>