10081677wc / blog

78 stars 6 forks source link

通过 CSS3 选择器根据子元素数量的不同定义样式 #7

Open 10081677wc opened 6 years ago

10081677wc commented 6 years ago

我们经常会遇到这样的问题:

导航栏根据某些条件的不同,显示出不同数量的选项卡

那么如何通过 CSS3 的选择器实现这样的需求呢?代码如下。

ul {
  /* one item */
  /* 是第一个子元素,同时也是倒数第一个子元素 */
  /* 即导航栏中只有一个选项卡的情况 */
  li:first-child:nth-last-child(1) {
    width: 100%;
  }

  /* two items */
  /* 是第一个子元素,同时也是倒数第二个子元素 */
  /* 即导航栏中只有两个选项卡的情况 */
  /* ~ 第一个子元素后面的所有兄弟元素 */
  li:first-child:nth-last-child(2),
  li:first-child:nth-last-child(2) ~ li {
    width: 50%;
  }

  /* three items */
  li:first-child:nth-last-child(3),
  li:first-child:nth-last-child(3) ~ li {
    width: 33.3333%;
  }

  /* four items */
  li:first-child:nth-last-child(4),
  li:first-child:nth-last-child(4) ~ li {
    width: 25%;
  }
}