1

Hello everyone in my case I want to target the 3 element for example, and I have the tags different, the 3 element can be p or div or something else, so I want to just target the 3 element what ever it is, i want to select always the 3 element.

Can I do that with CSS, if any help?

For example :

<div>
  <p></p>
  <span><span>
  <div></div> //3 element here is div
  <a></a>
</div>

Or :

<div>
  <div></div>
  <span><span>
  <p></p> //3 element here is p
  <a></a>
</div>
4
  • Your examples aren't very helpful, because you don't say what you want to do with them. Do you mean you want to style the third element? If so, look up "nth child".
    – IMSoP
    Commented Mar 16, 2021 at 11:19
  • Do you mean like this div > *? or div *:nth-child(3) or?
    – m4n0
    Commented Mar 16, 2021 at 11:19
  • Does this answer your question? Select all child elements recursively in CSS
    – coagmano
    Commented Mar 16, 2021 at 11:19
  • ^^ This one is kinda the reverse of your question, but explains the difference between the way to select all children and all descendants
    – coagmano
    Commented Mar 16, 2021 at 11:20

2 Answers 2

5
  1. If you would always have 4 tags, and want to target first 3,

div > *:not(:last-child){
  background-color: red;
}
<div>
  <p>AAAAAAAAAAAAAAA</p>
  <span>AAAAAAAAAAAAAAA</span>
  <div>AAAAAAAAAAAAAAA</div>
  <a>AAAAAAAAAAAAAAA</a>
</div>

  1. You could also target first 3 elements like below,

div > *:nth-child(-n+3){
  background-color: red;
}
<div>
  <p>AAAAAAAAAAAAAAA</p>
  <span>AAAAAAAAAAAAAAA</span>
  <div>AAAAAAAAAAAAAAA</div>
  <a>AAAAAAAAAAAAAAA</a>
</div>

3
  • i just want to target always 3 element whatever it is
    – coding mv
    Commented Mar 16, 2021 at 11:26
  • div > :nth-child(1), div > :nth-child(2), div > :nth-child(3){ background: red; } Commented Mar 16, 2021 at 11:28
  • code 7 , I have updated the answer. You could also check the 2nd way. Commented Mar 16, 2021 at 11:32
0

if you only want to select first three child of a parent div(or any other element), you can do something like this,

.parent:nth-child(1),
.parent:nth-child(2),
.parent:nth-child(3){
   //Your styles
}

Above code would select 1st, 2nd and 3rd child of the parent div to which i gave a class of parent. Also, if you want to select all the child of that parent div you could simply do as,

.parent > *{
  //Your styles
}

this code would select all the child of the .parent div

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.