<分区>
标签 html css 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 在容器内包装时会重置。是否有可能即使在容器内也不会重置?
实际结果:
预期结果
w3schools 链接:https://www.w3schools.com/code/tryit.asp?filename=FPLP7CUMGSPD
最佳答案
不幸的是,仅仅使用 :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>
希望对您有所帮助。
关于html - CSS nth-child : How will nth-child will work even inside a container,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49424517/