How to create an effect when hovering over (hover) with CSS

The following article will show you how to create fun effects, change colors in the form of gradients, when users hover over a certain part of the website.

Website designers are certainly no stranger to CSS - the tool is still used to 'change clothes' for the website interface.The following article will show you how to create fun effects, change colors in the form of gradients, when users hover over a certain part of the web page.

How to create an effect when hovering over (hover) with CSS Picture 1
Gradient effect when hovering over the button

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:

  1. Select the element and wait until the user moves the mouse over it.
  2. Calculate the position corresponding to the element.
  3. Save coordinates in CSS variables.

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;
}
}
  1. Wrap the text inside the span to prevent the gradient from overflowing.
  2. Start with the 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.
  3. Use coordinates to follow the mouse pointer.
  4. Use 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:

  1. CSS is so powerful that it is possible to get anonymous Facebook user information
  2. Using only HTML and CSS code, one can create a masterpiece full of aesthetics like this
  3. Top 5 popular CSS Framework that you should keep in mind
4.3 ★ | 3 Vote | 👨 945 Views
« PREV POST
NEXT POST »