1. id选择器

<style>
    #container {
        width: 100px;
    }
</style>
<body>
    <div id="container"></div>
</body>

2. class选择器 | 类选择器

<style>
    .container {
        width: 100px;
    }
</style>
<body>
    <div class="container"></div>
</body>

3. 元素选择器

<style>
    div {
        width: 100px;
    }
</style>
<body>
    <div></div>
</body>

4. 通用选择器

<style>
    *{
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }
</style>
<body>
    <div></div>
</body>

5. 属性选择器

<style>
    /* 存在title属性的<a> 元素 */
    a[title] {
        color: purple;
    }
    /* 存在href属性并且属性值匹配"https://example.org"的<a> 元素 */
    a[href="https://example.com"]
    {
        color: green;
    }
    /* 存在href属性并且属性值包含"example"的<a> 元素 */
    a[href*='link'] {
        font-size: 2em;
    }
    /* 存在href属性并且属性值结尾是".org"的<a> 元素 */
    a[href$='.org'] {
        font-style: italic;
    }
    /* 存在class属性并且属性值包含以空格分隔的"logo"的<a>元素 */
    a[class~='logo'] {
        padding: 2px;
    }
    /* 表示带有以 class 命名的属性,且属性值是以 link6 开头的元素。 */
    a[class$='link7'] {
        color: red;
    }
</style>
<body>
    <a href="#" title="链接">link1</a>
    <a href="https://example.com">link2</a>
    <a href="https://link.com">link3</a>
    <a href="https://link2.org">link4</a>
    <a class="link logo">link5</a>
    <a class="link621312">link6</a>
    <a class="asdblink7">link7</a>
</body>

6. 选择器列表

<style>
    a,
    p {
        color: red;
    }
</style>
<body>
    <a href="#">1</a>
    <p></p>
</body>

7. 后代选择器

<style>
    ul.container li {
        color: red;
    }
</style>
<body>
    <ul class="container">
        <li>idx</li>
        <li>idx</li>
        <li>idx</li>
    </ul>
</body>

8. 一般兄弟选择器

<style>
    p ~ span {
        color: red;
    }
</style>
<body>
    <span>This is not red.</span>
    <p>Here is a paragraph.</p>
    <code>Here is some code.</code>
    <span>And here is a span.</span>
</body>

8. 相邻兄弟选择器

<style>
    li:first-of-type + li {
        color: red;
    }
</style>
<body>
    <ul>
        <li>One</li>
        <li>Two!</li>
        <li>Three</li>
    </ul>
</body>

9. 伪类

<style>
    p:hover {
        color: red;
    }
</style>
<body>
    <p>hover</p>
</body>

css 优先级

选择器的优先级由四个部分相加

  1. 千位: 如果声明在 style 的属性(内联样式)则该位得一分。这样的声明没有选择器,所以它得分总是1000。
  2. 百位: 选择器中包含ID选择器则该位得一分。
  3. 十位: 选择器中包含类选择器、属性选择器或者伪类则该位得一分。
  4. 个位:选择器中包含元素、伪元素选择器则该位得一分。
选择器 千位 百位 十位 个位 优先级
h1 0 0 0 1 0001
h1 + p::first-letter 0 0 0 3 0003
li > a[href*="en-US"] > .inline-warning 0 0 2 2 0022
#identifier 0 1 0 0 0100
内联样式 1 0 0 0 1000

比较时,按照首位开始比较谁大,比如千位为1,那么优先级最高,如果千位为0,那么看百位,有id就加一,谁大谁优先级高
1000 > 0100 > 0010 > 0001 > 0000
1000 > 0200 > 0030 > 0009 > 0000

*优先级最低 为 0000

如果使用vscode,在定义style时,可以鼠标划入类,会显示优先级,如下图:
CSS 选择器以及优先级

CSS 选择器以及优先级

CSS 选择器以及优先级

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。