coding mv
coding mv

Reputation: 13

how to target an element child in css

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>

Upvotes: 1

Views: 2195

Answers (2)

Vikas Gupta
Vikas Gupta

Reputation: 1231

  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>

Upvotes: 5

soraku02
soraku02

Reputation: 340

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

Upvotes: 0

Related Questions