Mayank Pandya
Mayank Pandya

Reputation: 1623

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.

Upvotes: 5

Views: 33243

Answers (4)

TheBaj
TheBaj

Reputation: 1141

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.

Upvotes: 1

chiliNUT
chiliNUT

Reputation: 19573

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

Upvotes: 4

Ashis Kumar
Ashis Kumar

Reputation: 6544

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>

Upvotes: 4

adnrw
adnrw

Reputation: 1040

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

Your CSS with > only selects direct descendants

Upvotes: 13

Related Questions