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>
coding mv
  • 13
  • 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 Mar 16 '21 at 11:19
  • Do you mean like this `div > *`? or `div *:nth-child(3)` or? – m4n0 Mar 16 '21 at 11:19
  • Does this answer your question? [Select all child elements recursively in CSS](https://stackoverflow.com/questions/4910077/select-all-child-elements-recursively-in-css) – coagmano Mar 16 '21 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 Mar 16 '21 at 11:20

2 Answers2

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>
Vikas Gupta
  • 1,183
  • 1
  • 10
  • 25
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

soraku02
  • 282
  • 3
  • 11