CSS 选择器以及优先级

  • CSS 选择器以及优先级已关闭评论
  • 181 次浏览
  • A+
所属分类:Web前端
摘要

css 优先级
行内 > id > class > 属性 > 标签|伪元素


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 优先级
行内 > id > class > 属性 > 标签|伪元素