CSS nth-child:nth-​​child如何在容器

时间:2018-03-22 09:07:34

标签: html css css3 css-selectors

<!DOCTYPE html>
<html>
<head>
<style> 
.zebra:nth-child(odd) {
    background: red;
}
</style>
</head>
<body>

<p class="zebra">Paragraph</p>
<p class="zebra">Paragraph</p>
<p class="zebra">Paragraph</p>

<div>
  <p class="zebra">Paragraph Inside</p>
  <p class="zebra">Paragraph Inside</p>
</div>

<p class="zebra">Paragraph</p>
<p class="zebra">Paragraph</p>
<p class="zebra">Paragraph</p>

<div>
  <p class="zebra">Paragraph Inside</p>
  <p class="zebra">Paragraph Inside</p>
</div>

<p class="zebra">Paragraph</p>
<p class="zebra">Paragraph</p>
<p class="zebra">Paragraph</p>

<p><b>Note:</b> Internet Explorer 8 and earlier versions do not support the :nth-child() selector.</p>

</body>
</html>

上面有一系列段落zebra类,但nth-child在容器内包装时重置。是否有可能即使在容器内也不会重置?

实际结果:

Result of above code

预期结果

Expected Result

w3schools链接:https://www.w3schools.com/code/tryit.asp?filename=FPLP7CUMGSPD

1 个答案:

答案 0 :(得分:1)

不幸的是,仅使用:nth-child伪类就无法做到这一点。

但是,您可以使用JQuery在页面上获取类的所有奇怪实例,并为它们添加一个类。使用此类,您可以根据需要设置样式。

一个例子:

$('.zebra:odd').addClass('highlight');
.highlight {
    background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<style> 

</style>
</head>
<body>

<p class="zebra">Paragraph</p>
<p class="zebra">Paragraph</p>
<p class="zebra">Paragraph</p>

<div>
  <p class="zebra">Paragraph Inside</p>
  <p class="zebra">Paragraph Inside</p>
</div>

<p class="zebra">Paragraph</p>
<p class="zebra">Paragraph</p>
<p class="zebra">Paragraph</p>

<div>
  <p class="zebra">Paragraph Inside</p>
  <p class="zebra">Paragraph Inside</p>
</div>

<p class="zebra">Paragraph</p>
<p class="zebra">Paragraph</p>
<p class="zebra">Paragraph</p>

<p><b>Note:</b> Internet Explorer 8 and earlier versions do not support the :nth-child() selector.</p>

</body>
</html>

我希望这会有所帮助。