我正在使用 LESS 并希望匹配一个类型为文本的特殊输入。
目前,我正在这样做:
td {
input[type=text] {
width: 100px;
}
}
对于我的第二个类型复选框输入,我需要另一个宽度。我试过这个:
td {
input[type=text] {
width: 100px;
&:nth-child(2) {
width: 40px;
}
}
}
但这行不通。有什么想法可以将 [type=text]
与 :nth-child()
结合起来吗?
最佳答案
您的 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
作为第二个 child ,那么您的输入将不再是第二个 child ,因为该位置已被标签占用。
如果您在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;
}
关于css - 结合 [attribute=value] 与 :nth-child(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11553619/