§ ITPOW >> 文档 >> CSS

纯 CSS,根据子元素数量,自动排列菜单项宽度

作者:vkvi 来源:ITPOW(原创) 日期:2021-5-6

或者你也可以不看本文的传统方法,使用 flex 布局,轻松实现:CSS 3 的 flex 布局

当菜单项为 2 个时,每个菜单项宽度 50%。

当菜单项为 3 个时,每个菜单项宽度 33.33%。

当菜单项为 4 个时,每个菜单项宽度为 25%。

……

我希望写个 CSS 一劳永逸,希望这个 CSS 能够自动识别有多少个菜单项。

利用 nth-of-type 和 nth-last-of-type

.nav ul li:nth-of-type(1):nth-last-of-type(2),
.nav ul li:nth-of-type(2):nth-last-of-type(1) { width:50%; }

.nav ul li:nth-of-type(1):nth-last-of-type(3),
.nav ul li:nth-of-type(2):nth-last-of-type(2),
.nav ul li:nth-of-type(3):nth-last-of-type(1) { width:33.33%; }

.nav ul li:nth-of-type(1):nth-last-of-type(4),
.nav ul li:nth-of-type(2):nth-last-of-type(3),
.nav ul li:nth-of-type(3):nth-last-of-type(2),
.nav ul li:nth-of-type(4):nth-last-of-type(1) { width:25%; }

如上,写了几个示例,利用了取巧的方式:

  • 正数第 1 个,倒数第 2 个,表示总共有 2 个,当前第 1 个。

  • 正数第 1 个,倒数第 3 个,表示总共有 3 个,当前第 1 个。

  • 正数第 1 个,倒数第 4 个,表示总共有 4 个,当前第 1 个。

相关文章