你真的懂CSS3的伪元素::before吗?

2,453 阅读2分钟

一、属性介绍

1、::before是在使用它的元素的内容前面插入内容

我们可以看到'哈哈'是插入在P元素的内容的前面而不是P元素本身的前面

2、::before的content属性是必须的

我们可以看到第二张图片加了content:''后,红色小块就显示出来了

3、::before的content可以是url

4、::before的content可以是attr

5、::before的content可以是counter

6、::before对img元素无效

我们可以看到'哈哈'显示不出来,原因是img元素是没有内容的

二、应用

1.清除浮动

2.面包屑导航

3.小三角

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="./css/all.min.css">
    <title>before</title>
    <style>
  h2 {
    float: left;
    width: 170px;
}
.popup {
    float: left;
    width: 340px;
    background: #727272;
    padding: 10px;
    border-radius: 6px;
    color: #FFF;
    position: relative;
    font-size: 12px;
    line-height: 20px;
}
.popup:before {
    content: "";
    display: block;
    width: 0; 
    height: 0; 
    border-top: 12px solid transparent;
    border-bottom: 12px solid transparent;
    border-right: 12px solid #727272; 
    position: absolute;
    top: 16px;
    left: -12px;
}
    </style>
</head>
<body>
   <h2>什么是CSS3?</h2>
   <div class="popup">
    CSS3是CSS(层叠样式表)技术的升级版本,于1999年开始制订,2001年5月23日W3C完成了CSS3的工作草案,主要包括盒子模型、列表模块、超链接方式、语言模块、背景和边框、文字特效、多栏布局等模块 
   </div>
</body>
</html>

4.消息提示

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="./css/all.min.css">
    <title>before</title>
    <style>
      .container a[data-tip]{
        font-size: 20px;
        text-decoration: none;
        position: relative;
      }
      a::after{
          content: attr(data-tip);
          position: absolute;
          white-space: nowrap;
          top:120%;
          padding: 5px;
          background: rgba(153, 146, 146, 0.5);
          left: -100%;
          display: none;
        }
        a[data-tip]:hover::after{
            display: block;
        }
    </style>
</head>
<body>
 <div class="container">
     平时有事没事我喜欢在
     <a href="#" data-tip="百度是一个搜索东西的网站">百度</a>
     上面搜索东西
 </div>
</body>
</html>

5.其他酷炫效果

代码地址:github.com/fanxuewen/e…