CSS3 伪元素选择器

102 阅读1分钟
  • before和after
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    /* 伪元素:伪 = 假的  元素 = 标签  (:before :after css2 不推荐)
       标志性符合: 双冒汗(::)
       ::before ::after 必须得有 content 属性
    */
    /* span::before {
      content: "今天";
    }
    span::after {
      content: "真好";
    } */
    div {
      width: 100px;
      height: 100px;
      border: 1px solid #000;
      margin: 10px;
      padding: 20px;
    }
    div::before {
      content: "在前面";
      color: red;
      background-color: pink;
      width: 50px;
      height: 50px;
      display: inline-block;
    }
    div::after {
      content: "在后面";
      color: gray;
    }
  </style>
</head>
<body>
  <!-- 元素 标签 节点 -->
  <!-- <span>今天</span><span>天气</span><span>真好</span> -->
  <!-- <span>天气</span> -->
  <div>11</div>
</body>
</html>

  • first-letter
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    /* 伪元素选择器 */
    /* 选中第一个字母 */
    li::first-letter {
      color: red;
      font-size: 30px;
    }
  </style>
</head>
<body>
  <ul>
    <li>dzm</li>
    <li>222</li>
    <li>xyq</li>
  </ul>
</body>
</html>

  • first-line
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    div {
      width: 200px;
      background-color: yellow;
    }
    div::first-line {
      color: red;
    }
  </style>
</head>
<body>
  <div>
    爱上了看的见爱丽丝的爱上了看的见爱丽丝的爱上了看的见爱丽丝的爱上了看的见爱丽丝的爱上了看的见
  </div>
</body>
</html>

  • selection
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    div {
      margin-bottom: 30px;
      background-color: yellow;
      width: 100px;
    }
    div::first-letter {
      font-size: 30px;
      float: left;
      color: blue;
    }
    div::first-line {
      color: red;
    }
    /* 鼠标拖拽选中的区域 */
    div::selection {
      background-color: red;
    }
  </style>
</head>
<body>
  <div>爱丽丝肯德基爱丽丝肯德基卢卡斯记得开拉丝机的卢卡斯记得开垃圾是考虑到静安寺考虑到</div>
  <div>爱丽丝肯德基爱丽丝肯德基卢卡斯记得开拉丝机的卢卡斯记得开垃圾是考虑到静安寺考虑到</div>
  <div>爱丽丝肯德基爱丽丝肯德基卢卡斯记得开拉丝机的卢卡斯记得开垃圾是考虑到静安寺考虑到</div>
</body>
</html>
  • demo 效果: