首页 > 解决方案 > 定位第二个元素和之后的第三个兄弟元素

问题描述

我有一个网格,我想定位网格中的第二个项目,然后是之后的每个第三个项目。

就硬编码的 CSS 而言,它看起来像这样:

.archive-article:nth-child(2),
.archive-article:nth-child(5),
.archive-article:nth-child(8), 
.archive-article:nth-child(11) {
   top: 2rem;
}

我将如何使用一个 CSS 属性来做到这一点?我试过.archive-article:nth-child(2n + 3)了,但这不起作用。

是否可以用一个属性/值实际做到这一点?

非常感谢任何帮助或建议

标签: csscss-selectors

解决方案


3n从第二个兄弟姐妹 ( ) 开始,定位每第三个兄弟姐妹 ( 2)。

section:nth-child(3n + 2) {
  background-color: lightgreen;
}

section {
  text-align: center;
  margin-bottom: 5px;
}
<article>
  <section>1</section>
  <section>2</section>
  <section>3</section>
  <section>4</section>
  <section>5</section>
  <section>6</section>
  <section>7</section>
  <section>8</section>
  <section>9</section>
  <section>10</section>
  <section>11</section>
  <section>12</section>
  <section>13</section>
  <section>14</section>
</article>


推荐阅读