【问题标题】:Combine [attribute=value] with :nth-child()将 [attribute=value] 与 :nth-child() 结合
【发布时间】:2012-07-24 22:59:12
【问题描述】:

我正在使用 LESS,并且想要匹配类型为文本的特殊输入。

目前,我正在这样做:

td {
    input[type=text] {
        width: 100px;
    }
}

对于复选框类型的第二个输入,我需要另一个宽度。我试过这个:

td {
    input[type=text] {
        width: 100px;

        &:nth-child(2) {
             width: 40px;
        }
    }
}

但这行不通。任何想法如何将[type=text]:nth-child() 结合起来?

【问题讨论】:

  • 没有时间使用 LESS 进行测试,但可能的解决方法是使用 input[type=text]:nth-child(2) 而不是嵌套。然后,如果它仍然不起作用,那就是选择器的错误。如果是这样,那么它可能是您正在使用的 LESS 程序中的一个错误。

标签: css less css-selectors


【解决方案1】:

您的 LESS 应转换为以下 CSS,且没有任何错误:

td input[type=text] {
    width: 100px;
}

td input[type=text]:nth-child(2) {
    width: 40px;
}

但是,如果您将其他元素作为文本输入的同级元素,则这些元素可能会干扰 :nth-child() 声明,因为 :nth-child() 仅查看元素相对于同一父级中所有其他同级元素的位置,而不是仅适用于其他同类元素(即input[type=text])。例如,如果您将 label 作为第二个孩子,那么您的输入将不再是第二个孩子,因为该位置已被标签占据。

如果您在td 中的唯一输入是所有[type=text],您应该可以改用:nth-of-type()

// LESS

td {
    input[type=text] {
        width: 100px;

        &:nth-of-type(2) {
             width: 40px;
        }
    }
}
/* CSS */

td input[type=text] {
    width: 100px;
}

td input[type=text]:nth-of-type(2) {
    width: 40px;
}

但请记住,它只查看元素名称 input 而不是 [type=text] 属性!

或者,如果您知道只有两个文本输入,您可以使用通用同级选择器来获取第一个输入之后的那个

// LESS

td {
    input[type=text] {
        width: 100px;

        & ~ input[type=text] {
             width: 40px;
        }
    }
}
/* CSS */

td input[type=text] {
    width: 100px;
}

td input[type=text] ~ input[type=text] {
    width: 40px;
}

【讨论】:

    猜你喜欢
    • 2013-05-26
    • 1970-01-01
    • 2011-08-24
    • 1970-01-01
    • 2019-01-06
    相关资源
    最近更新 更多