Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to match from beginning in css nth-of-child selector?

I want to select the first div until div number three.

So I use this selector:

div:nth-of-type(1) ~ div:nth-of-type(3) {
  border:1px solid red;
}

But it only match the 3 div. why? how to match from the begining until 3?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

div:nth-of-type(1) ~ div:nth-of-type(3) {
  border:1px solid red;
}
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>

>Solution :

You can use :nth-child selector with -n+X pattern, where X is first X number of elements you need to target.

div:nth-child(-n+3) {
  border:1px solid red;
}
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading