Home >Web Front-end >CSS Tutorial >How Can I Efficiently Select Every Nth Element in CSS Using :nth-child()?

How Can I Efficiently Select Every Nth Element in CSS Using :nth-child()?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-22 10:26:40462browse

How Can I Efficiently Select Every Nth Element in CSS Using :nth-child()?

Selecting Every Nth Element in CSS

When dealing with a set of elements, it's often necessary to select specific elements at regular intervals. For example, you may want to select every fourth, sixth, or tenth element. Traditionally, this was achieved by explicitly specifying each nth element, such as:

div:nth-child(4),
div:nth-child(8),
div:nth-child(12),
div:nth-child(16)

However, there's a more efficient way to achieve this using the :nth-child() selector.

Using the ":nth-child()" Selector

The :nth-child() selector allows you to construct arithmetic expressions using the n variable. This means you can perform addition, subtraction, and coefficient multiplication.

To select every fourth element, you would use the following selector:

div:nth-child(4n)

This expression means that it will match every element that is 0n, 4n, 8n, and so on.

Handling Different Element Types

It's important to note that this expression assumes all child elements are of the same type. If you have elements of different types, such as h1 or p, you should use :nth-of-type() instead:

<body>
  <h1></h1>
  <div>1</div>  <div>2</div>
  <div>3</div>  <div>4</div>
  <h2></h2>
  <div>5</div>  <div>6</div>
  <div>7</div>  <div>8</div>
  <h2></h2>
  <div>9</div>  <div>10</div>
  <div>11</div> <div>12</div>
  <h2></h2>
  <div>13</div> <div>14</div>
  <div>15</div> <div>16</div>
</body>
div:nth-of-type(4n)

Counting from 1 vs. 0

In CSS, the n variable starts counting from 0. Therefore, if you use the expression 4n, it will select the elements with index 0, 4, 8, and so on. If you want to count from 1, you can use the expression 4n 1 instead.

The above is the detailed content of How Can I Efficiently Select Every Nth Element in CSS Using :nth-child()?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn