美文网首页
CSS 选择器

CSS 选择器

作者: 王难道 | 来源:发表于2016-10-13 16:50 被阅读0次

    常见的CSS选择器

    • 基础选择器(*,#id,.class,element)
    • 组合选择器
    • 属性选择器(h1,p,a...)
    • 伪类选择器
    • 伪元素选择器

    选择器的优先级

    从高到低分别是

    1. 在属性后面使用!important覆盖页面内任何位置定义的元素样式
    2. 作为style属性写在元素标签上的内联样式
    3. id选择器
    4. 类选择器
    5. 伪类选择器
    6. 属性选择器
    7. 标签选择器
    8. 通配符选择器
    9. 浏览器自定义

    class和id的使用场景

    • id选择器,只匹配特定id的元素
    • class选择器,匹配包含特定class的元素

    使用CSS选择器时为什么要划定适当的命名空间

    命名规则参考
    选择器的命名在各浏览器下的支持情况有所不同。因此,如果选择器的命名不规范,将影响各浏览器下,样式渲染不一致。

    以下选择器的意思

    • #header{}
      id为header的元素
    • .header{}
      类名包含header的元素
    • .header .logo{}
      类名包含header的元素的后代中类名包含logo的
    • .header.mobile{}
      类名包含header和mobile的元素
    • .header p, .header h3{}
      类名包含header的元素中的p元素和h3元素
    • #header .nav>li{}
      id为header的元素的类名包含nav的子元素的直接子元素li
    • #header a:hover{}
      id为header的子元素a的鼠标悬停效果

    伪类选择器

    • E:first-child,匹配第一个子元素且为元素E
    • E:first-of-type,匹配子元素为E的其中第一个,等同于:nth-of-type(1)
    • E:link,匹配所有未被点击的链接
    • E:visited,匹配所有已被点击的链接
    • E:active,匹配鼠标已经其上按下、还没有释放的E元素
    • E:hover,匹配鼠标悬停其上的E元素
    • E:focus,匹配获得当前焦点的E元素,常用于输入框
    • E:checked,匹配表单中被选中的radio或checkbox元素
    • E::selection,匹配用户当前选中的元素
    • E:nth-child(n),匹配其父元素的第n个子元素,第一个编号为1
    • E:nth-last-child(n),匹配其父元素的倒数第n个子元素,第一个编号为1
    • E:nth-of-type(n),与:nth-child()作用类似,但是仅匹配使用同种标签的元素
    • E:nth-last-of-type(n),与:nth-last-child() 作用类似,但是仅匹配使用同种标签的元素
    • E:last-child,匹配父元素的最后一个子元素,等同于:nth-last-child(1)
    • E:last-of-type,匹配父元素下使用同种标签的最后一个子元素,等同于:nth-last-of-type(1)
    • n的取值:1,2,3...2n+1, 2n, 4n-1...odd, even

    :first-child和:first-of-type的作用和区别

    • E:first-child,匹配第一个子元素且须为元素E,若第一个子元素不是E元素,则不选择
    • E:first-of-type,匹配子元素为E的其中第一个,
      即将子元素中的元素E选出,选择其中第一个

    读代码

    示例

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>readcode</title>
        <style>
            .item1:first-child {
                color: red;
            }
    
            .item1:first-of-type {
                background: blue;
            }
        </style>
    </head>
    
    <body>
        <div class="ct">
            <p class="item1">aa</p>
            <h3 class="item1">bb</h3>
            <h3 class="item1">ccc</h3>
        </div>
    </body>
    
    </html>
    
    • aa作为第一个子元素也是第一个P元素同时被.item1:first-child和.item1:first-of-type选择
    • bb作为第一个H3元素被.item1:first-of-type选择
    • ccc没有被选择

    text-align: center的作用以及对象

    • 作用:文本居中
    • 作用在块级元素上
    • 可以让块级元素中的文字或行内元素居中

    如果遇到一个属性想知道兼容性,在哪查看?

    Can I use

    本教程版权归饥人谷和作者所有,转载须说明来源。

    相关文章

      网友评论

          本文标题:CSS 选择器

          本文链接:https://www.haomeiwen.com/subject/tliwyttx.html