Is there a way in CSS by which I can access elements inside element. First element, Second Element?

Let’s say I have

  <div class='r1'>                <div> Apple </div>                <div> Banana </div>                <div> Orange </div>                <div> Tulip </div>   </div> 

I wanted to access each element inside r1 but I have to give each of them a separate id or class. Is there any way I just access it based on their number of position.

Such as

  .r1:first-child{      color:red;    }    .r1:second-child{      color:blue;     } 
Add Comment
2 Answer(s)

You can use the :nth-child() selector. For example:

.r1:nth-child(1) {   color: red; }  .r1:nth-child(2) {   color: blue; } 

You can also cool formula stuff like:

/* Will make every 5th element red, starting at the second one */ .r1:nth-child(5n+1) {   color: red; }  /* Will make the odd div elements blue */ .r1:nth-child(odd) div {   color: blue; } 
Add Comment
.ri:nth-child(1) {   color: red; }  .ri:nth-child(2) {   color: blue; } 

etc.

Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.