博客列表 >css选择器基础知识

css选择器基础知识

ROC-Y
ROC-Y原创
2020年04月08日 02:14:57827浏览

1.简单选择器

分为元素选择器和属性选择器2类。

  • 其中元素选择器包括div {...},群组选择器h1,h2,h3 {...},通配选择器 * {}
  • 属性选择器包括 *{...},类选择器 *.类名 {...},id选择器#id {...}
  • 当 class,id 选择器不限定被修改的元素类型时, 星号”*“可以省略
    举例:
  • (1)标签选择器
    • 使用标签名作为选择器的名称
      div { background-color:gray; color:white; }
  • (2)class选择器

    • 每个html标签都有一个属性 class

      1. <div class="haha">aaaaaaa</div>
      1. *.haha {
      2. background-color: orange;
      3. }
  • (3)id选择器

    • 每个html标签上面有一个属性 id
      1. <div id="hehe">bbbbb</div>
      2. #hehe {
      3. background-color: #333300;
      4. }
    • 优先级
    • style > id选择器 > class选择器 > 标签选择器

2.上下文选择器

  • 后代选择器,符号 空格
  • 父级选择器,符号 >
  • 相邻选择器,符号+
  • 子元素,符号~

  • (1)关联选择器

    1. <body>
    2. <div><h>hhhhhh</h>
    3. <p>wwwwwwww</p>
    4. <p>wwwwwwww</p>
    5. <p>wwwwwwww</p>
    6. </div>
    7. </body>
    8. /* 设置h标签相邻p标签的样式,嵌套标签里面的样式*/
    9. h+p {
    10. background-color: green;
    11. }

  • (2)组合选择器

    1. <body>
    2. <div><h>hhhhhh</h>
    3. <p>wwwwwwww</p>
    4. <p>wwwwwwww</p>
    5. <p>wwwwwwww</p>
    6. </div>
    7. </body>
    8. /* 把h和p标签设置成相同的样式,把不同的标签设置成相同的样式 */
    9. h,p {
    10. background-color: orange;
    11. }

3.伪类选择器

应用场景分为,结构伪类和表单伪类。

3.1结构伪类

  • 不分组匹配
    • 匹配第一个子元素:first-child
    • 匹配最后一个子元素:last-child
    • 选择元素的唯一子元素:only-child
    • 匹配任意位置的子元素:nth-child(n)
    • 匹配倒数任意位置的子元素:nth-last-child(n)
    • 针对匹配位置参数n,例如第3个元素的前面元素nth-child(n),则为 -n+3;后面则为n+3;如果是倒数2个,则为 nth-last-child(-n+2)
  • 分组匹配

    • 匹配第一个子元素:first-of-type
    • 匹配最后一个子元素:last-of-type
    • 选择元素的唯一子元素:only-of-type
    • 匹配任意位置的子元素:nth-of-type()
    • 匹配倒数任意位置的子元素:nth-last-of-type()
  1. <body>
  2. <h>hhhhh</h>
  3. <h>wwwwwwww</h>
  4. <h>wwwwwwww</h>
  5. <h>wwwwwwww</h>
  6. <p>mmmmmmmmm</p>
  7. <p>wwwwwwww</p>
  8. <p>wwwwwwww</p>
  9. <p>wwwwwwww</p>
  10. </body>
  1. /* p分组前2个 */
  2. p:nth-of-type(-n + 2) {
  3. background-color: grey;
  4. }
  5. /* p分组后2个 */
  6. p:nth-last-of-type(-n + 2) {
  7. background-color: coral;
  8. }

3.2 其它伪类

序号 选择器 描述
1 :active 向被激活的元素添加样式
2 :focus 向拥有键盘输入焦点的元素添加样式
3 :hover 当鼠标悬浮在元素上方时,向元素添加样式
4 :link 向未被访问的链接添加样式
5 :visited 向已被访问的链接添加样式
5 :root 根元素,通常是html
5 :empty 选择没有任何子元素的元素(含文本节点)
5 :not() 排除与选择器参数匹配的元素
  1. <style>
  2. a:active {
  3. background: red;
  4. }
  5. :focus {
  6. background: wheat;
  7. }
  8. select:hover {
  9. background: yellow;
  10. }
  11. a:link {
  12. background: lightgreen;
  13. }
  14. :root {
  15. background: lightseagreen;
  16. }
  17. </style>

4、总结

  • 元素和属性选择器,可以让我们有针对性的对已知元素和属性,进行样式设置。
  • 但是在存在多个相同元素,想要改变其中部分样式的时候,除了给这部分加上特殊的属性来区分之外,更简单的方式是使用伪类选择器。
  • 伪类选择器要特别注意匹配任意位置时候,参数n的表达式写法。
  • 其他伪类,可以针对元素或者事件有更多的样式选择,像focus,hover将会非常醒目。
声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议