html - CSS nth-child : How will nth-child will work even inside a container

标签 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 在容器内包装时会重置。是否有可能即使在容器内也不会重置?

实际结果:

Result of above code

预期结果

Expected Result

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/

上一篇:html - 使用 Bootstrap 在移动/桌面上进行另一个 View /订单的最佳实践

下一篇:javascript - 实现 ge1doot 的视差代码笔

相关文章:

html - 如何在 CSS 中选择具有特定类名的元素的 “last child”?

javascript - 从jade脚本添加到html元素

jquery - 格式化文本的数据标题中的 HTML 代码

javascript - 拆分字母并分配类别

css - 为什么 :not(>h1) not possible? 在纯 CSS 中有任何解决方法?

html - 使用 :checked css pseudo class with no javascript 使同级 <div> 可见

javascript - HTML5 pushState Clash w/Angular UI-Router URL 路由

css - 最后一个字后的 float 图像

python - django-tables2 为不同的行指定不同的属性

javascript - 禁止滚动文本