简体   繁体   中英

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.

you can just use .test input (which will apply to every input in <div class="test"> ).

Your CSS with > only selects direct descendants

div.test input{

}

will style all inputs nested in the div of class test

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

If you want to apply style to input using div with class="test", you can do like this

<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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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