在CSS中,我们可以使用“hover”伪类将鼠标悬浮在文字上时显示图片。.example{ background-image: url( example.jpg ); background-repea
在CSS中,我们可以使用“hover”伪类将鼠标悬浮在文字上时显示图片。
.example{ background-image: url("example.jpg"); background-repeat: no-repeat; background-size: cover; height: 200px; /*设置容器的高度*/ width: 200px; /*设置容器的宽度*/ position: relative; /*设置容器为相对定位*/ } .example:hover::before{ content:""; /*添加伪元素*/ background-image: url("example_hover.jpg"); background-repeat: no-repeat; background-size: cover; width: 200px; /*设置伪元素的宽度和高度,和父容器相同*/ height: 200px; position: absolute; /*设置伪元素绝对定位*/ top: 0; left: 0; }
在上述代码中,我们首先创建一个容器,使用“background-image”属性设置容器的背景图片。然后使用“position: relative”属性将容器设置为相对定位,为之后的设置做好准备。
接下来,我们使用“hover”伪类来检测鼠标是否悬浮在容器上。当检测到鼠标悬浮时,我们使用“::before”伪元素创建出一个新的元素,并使用“background-image”属性设置其背景图片。这个伪元素和容器的大小相同,并使用“position: absolute”属性将其绝对定位在容器的左上角。
这样,当鼠标悬浮在容器上时,就会出现一个遮盖在容器上的图片,达到了悬浮文字显示图片的效果。
粉丝
0
关注
0
收藏
0