:before和:after伪元素的常见用法总结

  1. 利用content属性,为元素添加内容修饰:

1) 添加字符串:
使用引号包括一段字符串,将会向元素内容中添加字符串。栗子:

a:after { content: "after content"; }

2) 使用attr()方法,调用当前元素的属性的值:
栗子:

a:after { content: attr(href); }
a:after { content: attr(data-attr); }

3)使用url()方法,引用多媒体文件:
栗子:

a::before { content: url(logo.png); }
  1. 使用counter()方法,调用计时器:
    栗子:
h:before { counter-increment: chapter; cotent: "Chapter " counter(chapter) ". " }
  1. 清除浮动:
.clear-fix { *overflow: hidden; *zoom: 1; }
.clear-fix:after { display: table; content: ""; width: 0; clear: both; }
  1. 特效妙用:
// CSS代码
a {
    position: relative;
    display: inline-block;
    text-decoration: none;
    color: #000;
    font-size: 32px;
    padding: 5px 10px;
}
a::before, a::after { 
    content: "";
  transition: all 0.2s;
}
a::before { 
  left: 0;
}
a::after { 
  right: 0;
}

a:hover::before, a:hover::after { 
  position: absolute;
}
a:hover::before { content: "\5B"; left: -20px; }
a:hover::after { content: "\5D"; right:  -20px; }

// HTML代码
<a href="#">我是个超链接</a>
  1. 特殊形状的实现:

举个栗子:(譬如对话气泡)

// CSS代码
.tooltip {
    position: relative;
    display: inline-block;
    padding: 5px 10px;
    background: #80D4C8;
}
.tooltip:before {
    content: "";
    display: block;
    position: absolute;
    left: 50%;
    margin-left: -5px;
    bottom: -5px;
    width: 0; 
    height: 0; 
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-top: 5px solid #80D4C8;
}

// HTML代码
<div class="tooltip">I'm a tooltip.</div>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,242评论 19 139
  • 使用CSS伪元素,before and after 画出一个五角星 before 和 after 顾名思义 其就是...
    falm阅读 9,731评论 1 7
  • 对中国用户来说,移动支付其实已经不是什么陌生事物,抢红包和支付宝早完成用户启蒙。但与这两者有区别的是,Apple ...
    LuxDark阅读 1,355评论 0 2
  • 最近身体不适。暂时休息下。不好意思,等我身体好了,会重新更文。
    韩译是头蠢驴阅读 336评论 2 1
  • 感恩大恩上师及诸佛菩萨的慈悲加持与护佑; 感恩历代宗亲及父母的养育之恩; 感恩格西老师、张慧老师带领我们学习金刚智...
    希热拉嘎阅读 180评论 0 0