伪元素
伪元素在某个元素上添加了一个页面中没有的元素,也即在添加到页面的伪元素是不存在与DOM树中的,伪元素常见的有::before , ::after,分别是在元素前添加、元素后添加,添加的伪元素是目标的子组件。下面的代码显示了基本的效果。
代码
<body>
<div class="parent">
<div class="child"></div>
</div>
</body>
.parent
{
background-color: antiquewhite;
width: 100vw;
height: 100vh;
}
.child
{
width: 50%;
height: 100px;
background-color: aqua;
position: relative;
transform: skewX(20deg);
left: 50%;
transform: translateX(-50%); /*搭配left实现居中效果*/
transition: all 2s ease;
}
.child::before
{
content: "";
z-index: 100;
position: absolute;/*因为父组件是relative方式,所以此组件的绝对定位是相对于div.child*/
left: 0;
transform: skewX(20deg);/*x轴倾斜*/
top: 0;
width: 50%; /*这里是使用父组件(div.child)宽度的100%*/
height: 100%;
background-color: black;
}
示例图
absolute定位的基点是相对于父组件,但若父组件的定位方式是static,定位的基点就会变成Html文档流,即此时的top,left,bottom,right是相对于标签html的。child::before的父组件是child,且child的定位方式是relative,所以child::before定位方式top left bottom right是相对于child的。
伪类与伪元素的结合
最常用的伪类是:hover,我们可以对上面的代码稍加修改,对伪元素施加鼠标悬停的动画效果。
.child:hover::before{
animation: child_animation 2s ease alternate;
}
@keyframes child_animation {
0%,100%{background-color: aquamarine}
50%{background-color: cadetblue}
}
注意
.child::before:hover是行不通的