Skip to content

伪元素

伪元素跟伪类的区别?

伪元素是用来表示元素的子元素,而伪类是用来表示元素的特殊状态。

伪元素的语法是::,伪类的语法是:;虽然伪元素使用:也起作用,但是::更有利于css进行识别。

伪元素的常用属性有::before::after::first-line::first-letter

伪元素的使用场景有插入内容、修饰元素、清楚浮动等。

使用

  1. 在文本前后添加小圆点:

html
<!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>
      body {
        margin: 0;
        padding: 0;
        display: flex;
        justify-content: center;
        align-items: center;
      }
      div {
        width: 95%;
        height: 100px;
        border: 5px solid #d2e9da;
        text-align: center;
        align-content: center;
      }
      span {
        position: relative;
      }
      span::before {
        content: " ";
        position: absolute;
        top: 6px;
        left: -20px;
        width: 10px;
        height: 10px;
        border-radius: 50%;
        background-color: #f8d7da;
        z-index: -1;
      }
      span::after {
        content: " ";
        position: absolute;
        top: 6px;
        left: 110px;
        width: 10px;
        height: 10px;
        border-radius: 50%;
        background-color: #f8d7da;
        z-index: -1;
      }
    </style>
  </head>
  <body>
    <div>
      <span>Hello World!</span>
    </div>
  </body>
</html>
  1. 清除浮动:
html
<!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>
      ul {
        border: 5px solid #d2e9da;
      }
      li {
        float: left;
        border: 1px solid #f0f0f0;
        margin: 15px;
        padding: 5px;
      }
      .clearfix:after {
        content: '';
        display: block;
        clear: both;
      }
    </style>
  </head>
  <body>
    <ul class="clearfix">
      <li>item1</li>
      <li>item2</li>
      <li>item3</li>
    </ul>
  </body>
</html>

Released under the MIT License.