Position the mouse cursor
The first step is to position the mouse pointer to track movement by 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 above lines of code correspond to 3 steps:
It only takes 9 lines of code to let CSS know the user's cursor position.
Create a gradient effect
Once you have the coordinates stored in the CSS variable, 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;
}
}
span
to prevent the gradient from overflowing.width
and height
of 0px
and bring it to 400px
when the user moves the mouse over.Don't forget to set the transition so the effect is smooth.radial-gradient
for the background and select the closest-side
circle so that the gradient ends at the closest center corner, if there are two positions that meet the requirement, it will be evenly distributed.When you get the mouse coordinates, you can create and apply many other interesting effects.Try it and don't forget to share it.
See more: