学习笔记——css伪类

95 阅读1分钟

1. :link(选中未访问过的超链接)& :visited(选中已经访问过的超链接)

<style>
  //未访问过设置为灰色
    .url:link {
      color: gray;
    }
  //访问过设置为绿色
    .url:visited {
      color: green;
    }
</style>
<a class="url" href="https://www.baidu.com">百度</a> 
<a class="url" href="https://www.google.com">谷歌</a>

2. :hover(选中鼠标移入的元素)

<style>
   .item {
      width: 300px;
      height: 300px;
      background: red;
    }

    .item:hover {
      background: green;
    }
</style>
<div class="item"></div>
<!-- 鼠标移入时,背景颜色为绿色,正常时为红色 -->

2.1. 扩展 hover联动其他元素

当我们给某个元素设置了hover属性后,我们可以联动修改其他盒子的css样式

  <style>
    .item {
      width: 300px;
      height: 300px;
      background: red;
    }

    .item1 {
      width: 100px;
      height: 100px;
      background: blue;
    }

    .item:hover {
      background: green;
    }

    .item:hover+.item1 {
      background: yellow;
    }
  </style>
  <body>
  <div class="item"></div>
  <div class="item1"></div>
</body>

鼠标移入前

鼠标移入后

3. :active(选中鼠标按下的元素)

<style>
    .item {
      width: 300px;
      height: 300px;
      background: red;
    }
   .item:active {
      background: yellow;
    }
  </style>
  <body>
  <div class="item"></div>
</body>

当元素被鼠标点击按住不放时,会把该元素颜色修改为yellow

3.1. 扩展 hover和active优先级,在写css样式时,应该先写hover再写active,否则active会不生效

4. :first-child(选中第一个子元素)& :last-child(选中最后一个子元素)

  <style>
    li:first-child {
      color:red
    }
    li:last-child {
      color:green
    }
  </style>
  <body>
  <ul class="ul-box">
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
  </ul>
</body>

5. :nth-child(an+b)(选中第(an+b)个子元素,a,b是常量,n的值从0开始递增)

  <style>
    /* 选中所有奇数的li 用2n+1或者odd*/
    li:nth-child(2n+1) {
      color: red
    }

    /* 选中所有偶数的li 用2n或者even*/
    li:nth-child(2n) {
      color: green
    }
    /* 选中特定规律下的li,我们要选择3,6,9...的li*/
    li:nth-child(3n + 3) {
      color: black
    }
  </style>
  <body>
  <ul class="ul-box">
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
    <li>6</li>
    <li>7</li>
    <li>8</li>
    <li>9</li>
    <li>10</li>
  </ul>
</body>