14

I have the following HTML code :

<div class="class1">
   <input type="text">
   <input type="text">
   <div class="class2">
       <input type="text">
       <input type="text">
   </div>
</div>

I want all the input fields to have a margin-left : 10px;

I know I can do the following :

.class1 > input {margin-left:10px}
.class1 > .class2 > input {margin-left:10px}

But I was wondering if I could do this with one line of CSS

.class1 >>> input {margin-left:10px}
//>>> meaning "has .class1 in his familly tree"
IggY
  • 2,869
  • 3
  • 26
  • 48

3 Answers3

21

You can just remove the direct descendant:

.class1 input {
    margin-left:10px
}

Alternatively if you wish to keep the direct descendant then you can have multiple selector rules:

.class1 > input,
.class1 > .class2 > input {
    margin-left:10px
}
Community
  • 1
  • 1
Curtis
  • 98,395
  • 62
  • 265
  • 345
2

Here is the way of applying CSS to child elements (for example)-

.class1 input {
 margin-left:15px;
}

.class1 > input {
    background-color:lightgreen;
}

.class1 > .class2 > input {
    background-color:lightblue;
}
<div class="class1">
   <input type="text">
   <input type="text">
   <div class="class2">
       <input type="text">
       <input type="text">
   </div>
</div>
Xahed Kamal
  • 2,093
  • 18
  • 39
2

CSS selectors are very flexible. for your requirement you can creator a selector as follows.

.class1 input {
    margin-left:10px
}

above selector will select all child input fields within .class1 div. it will also select input fields which are within .class2 as .class2 is also child of .class1

Nilesh Mahajan
  • 3,468
  • 19
  • 34