Use pseudo-elements to add a background image to the image when the mouse is hovered

Use pseudo-elements to add a background image to the picture when the mouse is hovered. This effect is frequently used on movie websites, mainly when the mouse is hovered, the playback icon is displayed. After clicking on the image link, you will enter the video details page , And the use of pseudo-elements is to make our html code more concise.

Key points:

1. Need to use absolute positioning and relative positioning to determine the position of the background image, the parent box is set to absolute positioning, and the pseudo-element background image is set to relative positioning.

2. The width and height of the background image should be consistent with the width and height of the parent box.

3. The background picture is not displayed by default, you need to set it to none with the display property, and then let it be displayed when the mouse is hovering, and set its display property to block when the mouse is hovering.

The following is the detailed code of using pseudo elements to add a background image to the image when the mouse is hovered:

<!doctype html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        *{
     
     
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        .img {
     
     
            position: relative;
            margin: 30px auto;
            width: 260px;
        }
        .img::before{
     
     
            content: '';
            display: none;
            position: absolute;
            height:100%;
            width: 100%;
            background:rgba(0,0,0,.2) url("img/icon.png") no-repeat center;
        }
        .img img{
     
     
            width: 100%;
            height: auto;
            border-radius:5px;
            padding: 10px;
            box-shadow: 0 5px 5px rgba(0,0,0,0.2);
        }
        .img:hover::before{
     
     
            display: block;
        }
    </style>
</head>
<body>
<div class="img">
    <img src="img/3.jpg" alt="">
</div>
</body>
</html>

The above simply implements the use of pseudo-elements to add a background image to the image when the mouse is hovered. In addition, we can add a transition effect to the background image with CSS3 transition elements to make the visual effect more comfortable.

Guess you like

Origin blog.csdn.net/Web_Jason365/article/details/108477115