This article brings the content is about how to use the pure CSS to achieve the background hover animation effect, there is a certain reference value, the need for a friend can refer to, I hope you have some help.
Effect Preview
Source code Download
Https://github.com/comehope/front-end-daily-challenges
Code interpretation
Defines the DOM, which contains an unordered table with a list item in the list:
<nav> <ul> <li>home</li> </ul></nav>
Center display:
body { margin:0; HEIGHT:100VH; Display:flex; Align-items:center; Justify-content:center; Background-color:teal;}
To hide the boot symbol from the front of the list item:
Nav ul { padding:0; List-style-type:none;}
Define button Container dimensions:
: root { font-size:10px;} Nav li { width:20rem; Height:7rem;}
To set the text style:
Nav li { font-size:20px; Text-align:center; Line-height:7rem; Font-family:sans-serif; Text-transform:uppercase; letter-spacing:1px;}
Create 2 background color blocks with pseudo-elements:
Nav li { position:relative;} Nav li::before,nav li::after { content: '; Position:absolute; Width:inherit; Height:inherit; top:0; left:0;} Nav li::before { background-color:white; Z-index:-1;} Nav li::after { background-color:goldenrod; Z-index:-2;}
Offset the background block to the right, and let the front background block drop shadows to increase the stereoscopic effect:
Nav li::before { box-shadow:0.2rem 0.2rem 0.5rem rgba (0, 0, 0, 0.2);} Nav li::after { transform:translate (1.5rem, 1.5rem);}
Next, increase the hover effect.
To set the ease time, both the main element and the pseudo element will have an easing effect:
Nav li { transition:0.3s;} Nav li::before,nav li::after { transition:0.3s;}
When hovering, the color of the 2 background color blocks is interchanged:
Nav li:hover::before { background-color:goldenrod;} Nav li:hover::after { background-color:white;}
At the same time, the back of the background color block moves to the left, and the button as a whole moves down to the right:
Nav li:hover { transform:translate (1.5rem, 1.5rem);} Nav li:hover::after { transform:translate ( -1.5rem, -1.5rem);}
Also, let the text change color on hover:
Nav li:hover { color:white;}
Add a few more buttons:
<nav> <ul> <li>home</li> <li>products</li> <li> services</li> <li>contact</li> </ul></nav>
Finally, increase the spacing between the buttons:
Nav li { margin:3rem;}
Done!