Home > Blockchain >  Css select first child inside another childs
Css select first child inside another childs

Time:12-15

I am trying to select the first child inside some other elements. This is the example.

<div >
 <div >
  <div ></div>
 </div>
 <div >
  <div ></div>
 </div>
 <div >
  <div >I NEED TO SELECT THIS</div>
 </div>
 <div >
  <div >NOT THIS</div>
 </div>
</div>

I want to select first occurrence of required. And also there can be arbitrary numbers div with .feature ( with .some) before i get to div which contains .required .

Can this be done ?

What i tried. (not working)

.parent .required:first-child {}
.parent .required:first-of-type {}

CodePudding user response:

.parent .feature .required:first-child {
 color: red;
}
    <div >
      <div >
       <div ></div>
     </div>
   <div >
     <div ></div>
   </div>
   <div >
    <div >I NEED TO SELECT THIS</div>
   </div>
   <div >
   <div >NOT THIS</div>
   </div>
  </div>

CodePudding user response:

You need to add a separate class for this. .parent .feature .required:first-child will work for the first childs of required class. In your code <div >I NEED TO SELECT THIS</div> and <div >NOT THIS</div> both are first childs of .parent class. So if you have at least two child of class then following works.

.parent .feature .required:first-child {
            color:red;

        }
<body>
        <div >
            <div >
                <div ></div>
            </div>
            <div >
                <div ></div>
            </div>
            <div >
                <div >I NEED TO SELECT THIS (First child)</div>
                <div >NOT THIS(second child)</div>
            </div>
            <div >
                <div >NOT THIS (This is also first child)</div>
            </div>
        </div>
    </body>

Hope you will understand the problem.

  • Related