温馨提示×

css伪类选择器怎么使用

小亿
115
2023-07-05 12:25:27
栏目: 编程语言

CSS伪类选择器用于选择元素的特定状态或位置。它们以冒号(:)开头,可以与元素名称、类选择器、ID选择器等组合使用。

以下是一些常用的CSS伪类选择器及其用法:

  1. :hover - 当鼠标悬停在元素上时应用样式。例如:a:hover { color: red; }

  2. :active - 当元素被激活(被点击)时应用样式。例如:button:active { background-color: yellow; }

  3. :focus - 当元素获得焦点时应用样式。例如:input:focus { border: 1px solid blue; }

  4. :first-child - 选择父元素的第一个子元素。例如:li:first-child { color: red; }

  5. :last-child - 选择父元素的最后一个子元素。例如:li:last-child { color: blue; }

  6. :nth-child(n) - 选择父元素的第n个子元素。例如:li:nth-child(2) { color: green; }

  7. :nth-of-type(n) - 选择父元素的第n个指定类型的子元素。例如:p:nth-of-type(odd) { color: red; }

  8. :not(selector) - 选择不匹配指定选择器的元素。例如::not(.hide) { display: block; }

  9. :first-of-type - 选择父元素的第一个指定类型的子元素。例如:p:first-of-type { font-weight: bold; }

  10. :last-of-type - 选择父元素的最后一个指定类型的子元素。例如:p:last-of-type { font-style: italic; }

这些只是一些常见的CSS伪类选择器,还有其他更多的选择器可供使用。了解这些选择器的用法可以帮助你更好地控制和样式化HTML元素。

0