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". Commented Mar 16, 2021 at 11:19
  • Do you mean like this div > *? or div *:nth-child(3) or? Commented Mar 16, 2021 at 11:19
  • Does this answer your question? Select all child elements recursively in CSS 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 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>

Sign up to request clarification or add additional context in comments.

3 Comments

i just want to target always 3 element whatever it is
div > :nth-child(1), div > :nth-child(2), div > :nth-child(3){ background: red; }
code 7 , I have updated the answer. You could also check the 2nd way.
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.