CSS 选择器以及优先级

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. 个位:选择器中包含元素、伪元素选择器则该位得一分。
选择器千位百位十位个位优先级
h100010001
h1 + p::first-letter00030003
li > a[href*="en-US"] > .inline-warning00220022
#identifier01000100
内联样式10001000

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

*优先级最低 为 0000

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值