教程 css tutorial

伪类选择器

伪类选择器允许你为特定状态或位置的元素定义样式,无需添加额外的类或ID,常用于交互效果或结构匹配。

以下是常见的伪类选择器:

  1. 交互状态类
    • :hover:鼠标悬停时触发
css
     a:hover { color: red; }
     ```


   - `:focus`:元素获取焦点时触发  

     
```css
     input:focus { outline: none; }
     ```


2. **结构伪类**
   - `:first-child`:选中父元素的第一个子元素  

     
```css
     li:first-child { font-weight: bold; }
     ```


   - `:last-child`:选中最后一个子元素  

     
```css
     li:last-child { color: gray; }
     ```


   - `:nth-child(n)`:选中特定序号的子元素  

     
```css
     tr:nth-child(odd) { background: #f9f9f9; }
     ```


3. **表单相关**
   - `:checked`:选中状态的表单项  

     
```css
     input:checked { background: yellow; }
     ```


   - `:disabled`:被禁用的表单项  

     
```css
     button:disabled { opacity: 0.5; }
     ```


伪类为元素状态控制和结构样式提供了强大支持,是CSS中不可或缺的选择工具。