2012-07-19 28 views
3

我在使用LESS并希望匹配其类型为文本的特殊输入。Combine [attribute = value]与:nth-​​child()

目前,我这样做:

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

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

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

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

但是,这是行不通的。任何想法如何结合[type=text]:nth-child()

+0

没有时间使用LESS进行测试,但可能的解决方法是使用'input [type = text]:nth-​​child(2)'而不是嵌套。然后,如果它仍然不起作用,这是选择器的错误。如果确实如此,那么它可能是您正在使用的LESS程序中的一个错误。 – 0b10011 2012-07-19 03:49:24

回答

5

你更不能转换为下面的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; 
}