必须记住的 30 类 CSS 选择器

31 Mar 2015


1. *

  * {
      margin: 0;
      padding: 0;
  }

2. #X //id选择器

3. .X

4. X Y //descendant(后代)选择器

  li a {
    text-decoration: none;
  }

5. X

6. X:visited 和 X:link

7. X+Y //相邻选择器

8. X>Y

9. X ~ Y //选择跟在目标元素后面的所有匹配的元素

10. X[title] //属性选择器

11. X[href="foo"]

12. X[href*="strongme"] //href属性值中包含strongme;使用^和$,分别表示字符串的开始和结束

13. X[href^="href"]

14. X[href$=".jpg"]

15. X[data-*="foo"]

16. X[foo~="bar"]

<a href="path/to/image.jpg" data-info="external image"> Click Me, Fool </a>
a[data-info~="external"] {
   color: red;
}
a[data-info~="image"] {
   border: 1px solid black;
}

17. X:checked //单选框和多选框

18. X:after //before和after这俩伪类

.clearfix {
  *zoom: 1;
}
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
  line-height: 0;
}
.clearfix:after {
  clear: both;
}

19. X::hover

p:hover {
  background: #e3e3e3;
}

20. X:not(selector) //反伪类

p:not(#container) {
  color: blue;
}

//把除id为container之外的所有p标签都选中

21. X::pseudoElement

p::first-line {
  font-weight: bold;
  font-size:1.2em;
}

p::first-letter {
  float: left;
  font-size: 2em;
  font-weight: bold;
  font-family: cursive;
  padding-right: 2px;
}

22. X:nth-child(n)

li:nth-child(3) {
   color: red;
}

23. X:nth-last-child(n)

li:nth-last-child(2) {
   color: red;
}

//假设你在一个ul标签中有N多的元素,而你只想获取最后三个元素,甚至是这样li:nth-child(397),你可以用nth-last-child伪类去代替它。

24. X:nth-of-type(n)

ul:nth-of-type(3) {
  border: 1px solid black;
}

//想象一下有5个ul标签。如果你只想对其中的第三个进行修饰,而且你也不想使用id属性,那你就可以使用nth-of-type(n)伪类来实现了,上面的那个代码,只有第三个ul标签会被设置边框。

25. X:nth-last-of-type(n) //倒序的获取标签

ul:nth-last-of-type(3) {
  border: 1px solid black;
}

26. X:first-child

27. X:last-child

28. X:only-child //几乎都不会用到这个伪类

29. X:only-of-type

li:only-of-type {
   font-weight: bold;
}

30. X:first-of-type

The 30 CSS Selectors you Must Memorize

必须记住的 30 类 CSS 选择器