伪元素 before 和 after 初探
使用了 CodePen 做演示,欢迎点击预览
定义
首先来看 MDN 的定义:
::before 创建一个伪元素,作为已选中元素的第一个子元素,常通过 content 属性来为一个元素添加修饰性的内容。
::after 创建一个伪元素,作为已选中元素的最后一个子元素,常通过 content 属性来为一个元素添加修饰性的内容。
语法
/* CSS3 语法 */ element::before { 样式 } /* (单冒号)CSS2 */ element:before { 样式 }
CSS3 引入 :: 用来区分伪类和伪元素。
使用
添加引号
首先看一下基本使用,在 q 标签的前后加上 « 和 »。
HTML
<q>Some quotes,</q> he said, <q>are better than none.</q>
CSS
q::before { content: "«"; color: blue; } q::after { content: "»"; color: red; }
Result
缸
绘制一个缸的正面图形。
HTML
<div class='vat'></div>
CSS
.vat { width: 160px; height: 160px; border-radius: 160px; background-color: #919191; position: relative; } .vat::before { content: ""; width: 160px; height: 40px; background-color: white; position: absolute; } .vat:after { content: ""; width: 160px; height: 10px; background-color: white; position: absolute; bottom: 0; }
Result
孔方兄
绘制一个圆形方孔的图形。
HTML
<div class="money"></div>
CSS
.money { width: 160px; height: 160px; border-radius: 160px; background-color: #8b653a; position: relative; } .money:after { content: ""; width: 50px; height: 50px; background-color: white; position: absolute; bottom: 55px; left: 55px; }
Result
待办清单
一个简单的代办清单,奇数次点击可打钩,偶数次点击取消打钩。
HTML
<ul> <li>Buy milk</li> <li>Take the dog for a walk</li> <li>Exercise</li> <li>Write code</li> <li>Play music</li> <li>Relax</li> </ul>
CSS
li { list-style-type: none; position: relative; margin: 2px; padding: 0.5em 0.5em 0.5em 2em; background: lightgrey; font-family: sans-serif; } li.done { background: #CCFF99; } li.done::before { content: ''; position: absolute; border-color: #009933; border-style: solid; border-width: 0 0.3em 0.25em 0; height: 1em; top: 1.3em; left: 0.6em; margin-top: -1em; transform: rotate(45deg); width: 0.5em; }
Javascript
var list = document.querySelector('ul'); list.addEventListener('click', function(ev) { if( ev.target.tagName === 'LI') { ev.target.classList.toggle('done'); } }, false);
Result
参考
[1] ::before