简体   繁体   English

将css样式应用于子元素

[英]Apply css style to child element

Here is an sample example 这是一个示例示例

<html>
<head>
    <style>
        .test > input {     //this is wrong.
            color:red;
        }
    </style>
</head>

<body>
    <div class="test">
        <div>
            <input></input>
        </div>
    </div>
</body>
</html>

What I want to do is apply a style to input element. 我想要做的是将样式应用于输入元素。 How to select a input element. 如何选择输入元素。 with the help of div's css style name. 在div的css样式名称的帮助下。

you can just use .test input (which will apply to every input in <div class="test"> ). 你可以使用.test input (这将适用于<div class="test">每个输入)。

Your CSS with > only selects direct descendants 你的CSS >只选择直接后代

div.test input{

}

will style all inputs nested in the div of class test 将样式嵌套在类test的div中的所有输入

div.test input:first-child{

}

will style only the first nested input. 将仅设置第一个嵌套输入的样式。

the ">" operator only styles directly descendent elements, so it will not style your inputs because you have div.test > div > input, the div in between div.test and input makes it so the input is not directly descendent to div.test “>”运算符只设置直接后代元素的样式,因此它不会设置您的输入样式,因为您有div.test> div>输入,div.test和输入之间的div使得输入不直接下降到div。测试

If you want to apply style to input using div with class="test", you can do like this 如果你想使用带有class =“test”的div将样式应用于输入,你可以这样做

<style>
    .test > div > input {
        color:red;
    }
</style>

As none of the other answers have mentioned this before, for this particular case you could also use the * selector. 由于之前没有其他答案提到过,对于这种特殊情况,您也可以使用*选择器。 It matches descendants that are grandchildren or later descendants. 它匹配孙子孙后代的后代。 You would use it like so: .test * input . 您可以这样使用它: .test * input

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM