Website designers are certainly no strangers to CSS – a tool that is still used to “change clothes” for website interfaces. The article below will show you how to create a fun effect, changing colors in the form of a gradient, when the user hovers over a certain part of the website.
Gradient effect when hovering over a button
Set the position of the mouse pointer
The first step is to position the mouse pointer to track movement using the code below.
document.querySelector('.button').onmousemove = (e) => {
const x = e.pageX - e.target.offsetLeft
const y = e.pageY - e.target.offsetTop
e.target.style.setProperty('--x', `${ x }px`)
e.target.style.setProperty('--y', `${ y }px`)
}
The lines of code above correspond to 3 steps:
- Select the element and wait until the user hovers over it.
- Calculate the position corresponding to the element.
- Save coordinates in CSS variable.
It only takes 9 lines of code for CSS to know the user's mouse cursor position.
Create gradient effects
Once you have the coordinates stored in CSS variables, you can use them anywhere in the CSS file.
.button {
position: relative;
appearance: none;
background: #f72359;
padding: 1em 2em;
border: none;
color: white;
font-size: 1.2em;
cursor: pointer;
outline: none;
overflow: hidden;
border-radius: 100px;
span {
position: relative;
}
&::before {
--size: 0;
content: '';
position: absolute;
left: var(--x);
top: var(--y);
width: var(--size);
height: var(--size);
background: radial-gradient(circle closest-side, #4405f7, transparent);
transform: translate(-50%, -50%);
transition: width .2s ease, height .2s ease;
}
&:hover::before {
--size: 400px;
}
}
- Wrap the text inside
span
to avoid the gradient from overflowing. - Start with
width
andheight
belong to0px
and brought it to the city400px
when the user hovers over it. Don't forget to set transitions so the effect is smooth. - Use coordinates so that the effect follows the mouse pointer.
- Use
radial-gradient
for background and select circleclosest-side
so that the gradient ends at the corner closest to the center, if there are 2 positions that meet the requirements, it will be evenly distributed.
Once you have the mouse coordinates, you can be creative and apply many other interesting effects. Try it out and don't forget to share.
See more: