PHP前端开发

CSS 选择器备忘单

百变鹏仔 4周前 (09-18) #CSS
文章标签 选择器

这是一个全面的 css 选择器备忘单,涵盖了您可能需要的所有基本和高级选择器:

1. 基本选择器

  * {    margin: 0;  }
  p {    color: blue;  }
  .container {    width: 100%;  }
  #header {    background-color: grey;  }

2. 属性选择器

  [type="text"] {    border: 1px solid black;  }
  [type="checkbox"] {    display: inline-block;  }
  [href^="https"] {    color: green;  }
  [href$=".pdf"] {    color: red;  }
登录后复制
  [class*="button"] {    font-weight: bold;  }

3. 组合选择器

  div p {    color: blue;  }
  ul > li {    list-style-type: none;  }
  h2 + p {    margin-top: 0;  }
  h2 ~ p {    color: green;  }

4. 伪类

  a:hover {    text-decoration: underline;  }
  input:focus {    border-color: blue;  }
  li:nth-child(2) {    color: red;  }
  p:nth-of-type(3) {    font-size: 1.2em;  }
  p:first-child {    font-weight: bold;  }
  p:not(.highlight) {    color: grey;  }

5. 伪元素

  p::before {    content: "note: ";    font-weight: bold;  }
  p::first-letter {    font-size: 2em;  }
  p::first-line {    font-style: italic;  }

6. 分组选择器

  h1, h2, h3 {    color: blue;  }

7. 特殊组合器

  div:empty {    display: none;  }
  input:enabled {    background-color: white;  }  input:disabled {    background-color: lightgrey;  }
  input:checked {    border-color: green;  }

8. 高级选择器

  tr:nth-child(even) {    background-color: lightgrey;  }
  li:nth-last-child(1) {    color: red;  }
  div:only-child {    border: 1px solid red;  }
  :root {    --main-color: blue;  }

9. 属性存在和值选择器

  [required] {    border: 2px solid red;  }
  [href^="http"] {    text-decoration: underline;  }
  [href$=".pdf"] {    color: red;  }
登录后复制
  [class*="icon"] {    background-color: yellow;  }

10. 其他选择器

  p:lang(en) {    color: blue;  }
  #section:target {    background-color: yellow;  }

结论

本备忘单涵盖了大多数 css 选择器,从基础到高级。以创造性的方式组合它们可以让您有效地定位特定元素并精确控制网页的外观。