利用伪元素实现需求

120 阅读1分钟

有一个需求要用到如图形状,用伪元素可以实现。伪元素相当于是子元素,两点可以证明。

  • 给伪元素设置绝对定位后,就像普通子元素一样往上找到有定位的元素。
  • 给父元素设置z-index: 2,伪元素设置z-index: 1,伪元素依然在上面。

image.png

// less代码
.figure {
    position: relative;
    width: 25px;
    height: 25px;
    border: solid 1px;

    &::after {
        position: absolute;
        content: "";
        width: 1px;
        height: 80%;
        top: -80%;
        left: 50%;
        background: black;
    }

    &::before {
        position: absolute;
        content: "";
        width: 1px;
        height: 80%;
        bottom: -80%;
        left: 50%;
        background: black;
    }
}