从两个父母CSS获取所有特定的孩子

时间:2017-09-05 08:38:46

标签: html css forms css-selectors

我想从两个不同的父类中选择所有input[type=text]个孩子。

对于下面的CSS,这是最干净的方法?

.secciones * input[type=text]
.subsecciones * input[type=text] {
    border: none transparent;
    background-color: white;
}

3 个答案:

答案 0 :(得分:2)

您应该删除通配符选择器。你几乎从不想要那个,因为它是一个非常宽泛的选择器:

.secciones input[type=text],
.subsecciones input[type=text] {
    border: none transparent;
    background-color: white;
}

Css从右到左解析,所以这个:.secciones input[type=text]
- 选择所有input[type=text]
- 对于每个匹配过滤器:检查它是.secciones

的(大)子项
<div class="secciones">
    <div>
        <input type="text" placeholder="I will match as one of my parents is .secciones" />
    </div>
    <input type="text" placeholder="I will match as one of my parents is .secciones" />
</div>

如果你添加通配符选择器,你基本上会说“检查input[type=text]是否是任何的孩子。使用*作为最正确的选择器,你可以从“选择一切”,这很多。

如果您想要选择器的直接儿童,您可以这样做:.secciones >input[type=text]
- 选择所有input[type=text]
- 对于每个匹配过滤器:检查它是.secciones直接子项

<div class="secciones">
    <div>
        <input type="text" placeholder="I will NOT match, my direct parent is NOT .secciones" />
    </div>
    <input type="text" placeholder="I will match, my DIRECT parent is .secciones" />
</div>

您可能希望使用*.hideNextElement + *

的示例
<div class="hideNextElement">click me to show next</div>
<div>I can be ANY element. With some JS I can become visible.</div>

答案 1 :(得分:1)

请勿使用 * 。 相反,请使用 , 。你应该这样做:

.secciones input[type=text],
.subsecciones input[type=text] {
    border: none transparent;
    background-color: white;
}

希望这有帮助!

答案 2 :(得分:1)

如果您想定位.secciones.subsecciones的所有后代,可以使用descendant combinator

.secciones input[type=text],
.subsecciones input[type=text] {
    border: none transparent;
    background-color: white;
}

如果您只想定位.secciones.subsecciones的直接下属(孩子),可以使用child combinator

.secciones > input[type=text],
.subsecciones > input[type=text] {
    border: none transparent;
    background-color: white;
}

您可以阅读有关使用组合器at the MDN的更多信息。

相关问题