【问题标题】:css nth-child and classescss nth-child 和类
【发布时间】:2012-03-14 18:19:11
【问题描述】:

我的 css nth-child 选择器有问题。 我在一个容器中有一个 3x3 元素的网格。这些元素有一个名为.square 的类。 使用.square:nth-child(3n+1),我选择该行的每个第一个元素并将其涂成绿色。 使用.square:nth-child(3n+3),我选择了行的最后一个元素并将其涂成红色。

这工作正常,直到在网格之前输出任何元素(例如<br>)。每增加一个新的<br>,顺序就会增加一个,就像<br> 被认为是.square

据我了解.nth-child,它应该选择.square 类的每三个元素。为什么它将它应用于任何元素,我如何才能实现我的初始目标?

提前致谢

http://www.hier-krieg-ich-alles.de/shop.php?cat=26491127728

问题出现在中间的盒子上。

【问题讨论】:

  • 请推送您的代码以便更好地理解

标签: class css css-selectors


【解决方案1】:

听起来你想要nth-of-type

您可能会发现有用的相关选择器是 :first-of-type:last-of-type:nth-last-of-type:only-of-type

【讨论】:

  • 是的。澄清一下,nth-child 只计算元素,所以.classname:nth-child 选择恰好有classname 并且恰好是第n 个孩子的元素。
  • 是的,这就是链接页面所说的:) nth-child 是常用的,因为它是第一次发布的(据我所知),但它实际上只在有限的情况下有用; nth-of-type 更有用,因为它做了大多数人认为 nth-child 所做的事情。
  • 相当。 first-child 实际上是第一个。奇怪的是,一开始甚至没有last-child
  • 你没有选择你认为的元素。您想要的 CSS 规则是左侧列的 .cat_outer_frame:nth-of-type(3n) { margin-left: 0; margin-right: 2%; },然后中间列没有样式(它从 .cat_outer_frame 继承 1% 的边距,最后是右侧列的 .cat_outer_frame:nth-of-type(3n+2) { margin-left: 2%; margin-right: 0; }
  • :nth-of-type() 也不选择元素的类!
【解决方案2】:

nth-child 仅适用于 html 元素,nth-child css 不知道类和 id,如果您想为类设置 nth-child,请使用 jquery 为该类添加一些自定义属性..

喜欢

jQuery('.square:nth-child(3n+3)').attr("act","dummy");

然后使用 css

div[act='dummy']{
 border : 1px solid red;}

【讨论】:

    猜你喜欢
    • 2023-03-30
    • 1970-01-01
    • 2018-07-30
    • 2014-08-01
    • 2021-11-20
    • 1970-01-01
    • 1970-01-01
    • 2019-06-11
    • 1970-01-01
    相关资源
    最近更新 更多