将[attribute = value]与:nth-​​child()结合使用

Ben*_*min 3 css css-selectors css3 less

我正在使用LESS并希望匹配类型为文本的特殊输入.

目前,我这样做:

td {
    input[type=text] {
        width: 100px;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

        &:nth-child(2) {
             width: 40px;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但这不起作用.任何想法如何结合[type=text]使用:nth-child()

Bol*_*ock 5

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

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

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

但是,如果您有其他元素作为文本输入的兄弟元素,则这些元素可能会干扰: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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)
/* CSS */

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

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

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

或者如果你知道你只有两个文本输入,你可以使用通用兄弟选择器来获取第一个输入后面的那个:

// LESS

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

        & ~ input[type=text] {
             width: 40px;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)
/* CSS */

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

td input[type=text] ~ input[type=text] {
    width: 40px;
}
Run Code Online (Sandbox Code Playgroud)