在 CSS 中,和 是可以添加到选择器以创建伪元素的关键字。伪元素将插入到与选择器匹配的元素中,在选择器中的任何内容之前或之后。
1.最简单的用法
// 页面
<div class="my_text">hello word</div>
// 样式
.my_text::before {
content: '';
}
.my_text::after {
content: '';
}
2.使用计数器显示计数
先上效果图
废话不多说,直接上代码:
// 页面
<div class="wrapper">
<input id="c1" type="checkbox"><label for="c1"></label>
<input id="c2" type="checkbox" checked><label for="c2"></label>
<input id="c3" type="checkbox" checked><label for="c3"></label>
<input id="c4" type="checkbox"><label for="c4"></label>
<input id="c5" type="checkbox"><label for="c5"></label>
<span>=</span>
<output></output>
</div>
// 样式
input:checked {
counter-increment: total;
}
output::before {
content: counter(total);
}
input {
position: absolute;
width: 1px;
clip: rect(0 0 0 0);
overflow: hidden;
white-space: nowrap;
}
label {
display: grid;
place-items: center;
width: 50px;
height: 50px;
background-color: #fff;
overflow: hidden;
}
input:focus + label {
outline: 2px solid #406f99;
}
input:checked + label::before {
content: '✔';
}
body {
box-sizing: border-box;
display: grid;
place-items: center;
min-height: 100vh;
margin: 0;
padding: 20px;
color: #406f99;
background-color: #cbd9e6;
font: 700 2.5rem/1 'Fira Mono', monospace;
}
.wrapper {
display: flex;
justify-content: space-between;
width: 100%;
max-width: 500px;
}
span, output {
height: 50px;
line-height: 50px;
}
3.结合图片
// 页面
<div data-lives="3"></div>
// 样式
div::before {
content:
url(https://assets.codepen.io/77020/8bit-mario.gif)' × 'attr(data-lives);
}
body {
box-sizing: border-box;
display: grid;
place-items: center;
min-height: 100vh;
margin: 0;
padding: 20px;
color: #fff;
background-color: #000;
font: 2.25rem/1 'Press Start 2P', monospace;
}
4.伪元素改变添加动画
// 页面
<div></div>
// 样式
div::before {
content: '';
animation: flip 2s linear infinite;
}
@keyframes flip {
from { content: 'Hello!'; }
to { content: 'Goodbye!'; }
}
body {
box-sizing: border-box;
display: grid;
place-items: center;
min-height: 100vh;
margin: 0;
padding: 20px;
color: #fe4365;
background-image: linear-gradient(45deg, #c5e0dc, #f9cdad);
font: 700 5rem/1 'Signika', sans-serif;
}
好了,分享到此结束!