利用hover 伪类实现元素切换

需求:【item-front元素】默认显示,【item-back元素】默认隐藏,当鼠标移至【item-front元素】时,隐藏该元素,并显示【item-back元素】。如下动图:

◆ 实现思路

利用【hover 伪类】和【opacity属性】来控制元素的显示与隐藏,达到元素切换效果。代码如下

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        .item {
            width: 200px;
            height: 200px;
            position: relative;
            background-color: #f5f5f5;
        }

        .item-front,
        .item-back {
            box-sizing: border-box;
            padding: 20px;
            background-color: #f5f5f5;
        }

        .item-front {
            position: absolute;
            z-index: 2;
            left: 0px;
            top: 0px;
            width: 100%;
            height: 100%;
            display: flex;
            flex-direction: row;
            justify-content: center;
            align-items: center;
            text-align: center;
            transition: 0.2s all;
            opacity: 1;
        }

        .item-back {
            position: relative;
            z-index: 1;
        }

        .item:hover .item-front {
            opacity: 0;
        }
    </style>
</head>

<body>
    <div class="item">
        <div class="item-front">
            <h2 class="font-title">行深膳食</h2>
        </div>
        <div class="item-back">
            <p>践行适合个人健康饮食模式并持之以恒</p>
        </div>
    </div>
</body>

</html>

关键点:1:【item-front元素】的【z-index】堆叠顺序比【item-back元素】高。2:【item-front元素】背景色【不能】透明,不然【item-back元素】会穿透【item-front元素】显示出来。2:【item-front元素】设置【position: absolute】绝对定位,达到两个元素相同位置堆叠效果。