background
The mouse hover to achieve the active effect compared to most of us is often done. Changing the color of text and images is a common routine. However, the resource I encountered is SVG and it is a remote resource, so I can only use the background image. Previously, I used the font icon, using the color attribute can control, how to operate the SVG background image?
The CSS filter properties
filter: none | blur(a) |brightness(a) |contrast(a) |drop-shadow(a) |grayscale(a) |hue-rotate(a) |invert(a) |opacity(a) |saturate(a) |sepia(a) |url(a);Copy the code
You can see the familiar or more, you can adjust blur, light and shade, contrast and so on. The property we need for this scenario is drop-shadow
drop-shadow (h-shadow v-shadow blur spread color)
Copy the code
There are many parameter types, which are not introduced here. The document has a detailed description.
Implementation approach
We mainly use offset and color parameters for this effect. The general idea is as follows
- Use filters to get familiar with creating an SVG image after hover, and then hide it
- After the hover user, use a transform to reverse the offset and display it
Create a red star with drop-shadow
.svg{
width:30px;
filter:drop-shadow(30px 0 red)
}
Copy the code
Then fill a box outside the img tag with overflow: Hidden to hide the red star and hover with a Transform offset
The complete code
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Static Template</title>
<style>
.img-box{ width:30px;overflow:hidden; }.img-box:hover .svg{transform:translateX(-30px); }.svg{ width:30px;filter:drop-shadow(30px 0 red)}
</style>
</head>
<body>
<div class="img-box">
<img class="svg" src="./demo.svg">
</div>
</body>
</html>
Copy the code
compatibility
It’s a great choice if you don’t need to be compatible with IE