lishengzxc / bblog

My Blog
https://github.com/lishengzxc/bblog/issues
178 stars 8 forks source link

diaodiao 的 CSS child 选择器 #8

Open lishengzxc opened 8 years ago

lishengzxc commented 8 years ago

diaodiao 的 CSS child 选择器

基础的概念和应用

选择器 🌰 🌰描述
:first-child p:first-child 选择属于父元素的第一个子元素的每个

元素。

:only-child p:only-child 选择属于其父元素的唯一子元素的每个

元素。

:nth-child(n) p:nth-child(2) 选择属于其父元素的第二个子元素的每个

元素。

:nth-last-child(n) p:nth-last-child(2) 同上,从最后一个子元素开始计数。
:last-child p:last-child 选择属于其父元素最后一个子元素每个

元素。

OK,基础的东西就描述到这里,本身大家应该都了解,接下来说一些进阶的应用。

进阶应用

申明下面所有例子有应用于以下结构:

<ul>
  <li>...<li>
  ...
</ul>

选择前 3 个 li

ul li:nth-child(-n + 3) {
  ...
}

选择后 3 个 li

ul li:nth-last-child(-n + 3) {
  ...
}

选择从第 3 个开始的以后的 li

ul li:nth-child(n + 4) {
  ...
}

选择从第 2 个到第 4 个 li

ul li:nth-child(n + 2):nth-child(-n + 4) {
  ...
}

选择前后从第 3 个开始的全部

ul li:nth-child(n + 3):nth-last-child(n + 3) {
  ...
}

选择从第 2 个到 第 4 个中的奇(偶)数个 li

ul li:nth-child(odd):nth-child(n + 2):nth-child(-n + 4) {
  ...
}

or

ul li:nth-child(even):nth-child(n + 2):nth-child(-n + 4) {
  ...
}

选择从第 2 个到 第 4 个中的 3 倍数个 li

ul li:nth-child(3n):nth-child(n + 2):nth-child(-n + 4) {
  ...
}

选择除了第 3 个的全部 li

ul li:not(:nth-child(3)) {
  ...
}

选择只有 2 个 li 的第 1 个

ul li:nth-last-child(2):first-child {
  ...
}

选择 li 最少满足 3 个的情况

ul li:nth-last-child(n + 3),
ul li:nth-last-child(n + 3) ~ li {
  ...
}

选择 li 最多满足 3 个的情况

ul li:nth-last-child(-n + 3):first-child,
ul li:nth-last-child(-n + 3):first-child ~ li {
  ...
}

选择 li 满足最少 5 个最多 10 个的情况

ul li:nth-last-child(n + 5):nth-last-child(-n + 10):first-child, 
ul li:nth-last-child(n + 5):nth-last-child(-n + 10):first-child ~ li {
  ...
}

参考链接