css - 结合 [attribute=value] 与 :nth-child()

标签 css less css-selectors

我正在使用 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/

相关文章:

CSS 背景附件不起作用,无法修复背景上的填充/边距

html - 将列内容与 Bootstrap 4 对齐

元素上的 Css 过渡在鼠标悬停时改变位置

javascript - 如何让 'grunt less' 自动运行 autoprefixer?

css - 我可以从不同的来源编译更少的文件吗?

python-3.x - 通过href属性的一部分查找元素

java - 按值选择元素

css - 想要将除指定div之外的整个页面设为灰度

css - Sublime Text Less2Css 禁用自动计算

html - nth-of-type(2) 是针对第一个类型?