css - 使用 :nth-child pseudo class, 是否可以选择由 2 个元素组分隔的 3 个元素组?

标签 css css-selectors

我正在构建砌体网格,但在计算出选择适当元素的代数时遇到了困难。

  • 2x 宽样式的元素:1, 7, 11, 17, 21, 27, ...
  • 2 倍高样式的元素:2、6、12、16、22、26、...

所有其他元素将由默认样式处理。

标记是:

<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  ...
</ul>

我无法完全找到用于我的 :first-child 伪类的模式。我附上了我要实现的目标的图片。

有没有数学天才准备好迎接[可能非常简单]的挑战?

grid

最佳答案

你可以这样对序列进行分类:

  • 1, 7, 11, 17, 21, 27, ... 包含 2 个子序列:

    • 1, 11, 21, ...
    • 7, 17, 27, ...

所以我们可以使用 2 个选择器::nth-child(10n + 1):nth-child(10n + 7)

  • 2, 6, 12, 16, 22, 26, ... 包含 2 个子序列:

    • 2, 12, 22, ...
    • 6, 16, 26, ...

所以我们可以使用 2 个选择器::nth-child(10n + 2):nth-child(10n + 6)

根据您的图像,我可以看到所有 1, 11, 21, ...7, 17, 27, ... 都应该有宽度about 66.66% (2/3) 和更大的 height 与其他单元格的默认高度相比。所有2, 12, 22, ...6, 16, 26, ... 的高度应该与 1, 11, 21, ...7, 17, 27, ... 并且它们与其他默认单元格具有相同的宽度(大约 33.33% 1/3).

所以我们可以这样设置 ul 的样式:

ul {
  width:500px; 
  list-style:none;
  border:20px solid gray;
  overflow:auto;
  padding:0;
}
ul > li {
  display:inline-block;
  float:left;
  width:33.33%;
  height:50px;
  border:2px solid lightgray;
  box-sizing:border-box;  
  text-align:center;
}
/* this is just to center the text vertically */
ul > li:before {
  content:'';
  display:inline-block;
  height:100%;
  vertical-align:middle;
}
ul > li:nth-child(10n + 1), ul > li:nth-child(10n + 7) {
  width:66.66%;
  height:80px;
}
ul > li:nth-child(10n + 2), ul > li:nth-child(10n + 6){
  height:80px;
}

Demo.

在上面的演示中,您可以看到所有内部元素周围都有一个 2px 的内边框,并且与 ul 的边框相邻,需要将其删除以适当的单元格为目标并删除适当的边框。这是 Updated Demo 哪个更复杂。

关于css - 使用 :nth-child pseudo class, 是否可以选择由 2 个元素组分隔的 3 个元素组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23814673/

相关文章:

html - 如何使部分根据大小将其他部分向下推?

css - 悬停时边框颜色变化

html - 如何使用 CSS 选择文本节点

html - 如何在不使用类或伪类的情况下选择表行?

html - CSS nth-child 表达式删除最后一行的底部边距

css - 使用 asciidoctor 产生的丰富的语法高亮

javascript - 如何让我的 Javascript 只显示一个以鼠标为中心的聚光灯?

html - CSS Sprite 以获得最大的可访问性?

css - Google Maps v3 - 防止 API 加载 Roboto 字体

css - 尝试将 CSS 类与第 N 个子选择器一起使用