/ Button

Stunning hover effects with CSS variables look like Grover

Stunning hover effects with CSS variables look like Grover

Grover button

Moving your mouse over the subscribe-button reveals a colorful gradient that follows your cursor as it moves.

The idea is simple, but the result is a button that stands out from the reset and waits to be clicked.

Track the position

The first thing we need is the position of the mouse.

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`)
 
}
  1. t the element and wait till the user moves his mouse across it
  2. Calculate the position relative to the element
  3. Save the coordinates in CSS variables

Yes, only 9 lines of code to let your CSS know where the user positions his mouse. The amount of effects you can achieve with this information is enormous. But let us finish the CSS first…

Animate the gradient

We now have the coordinates stored in CSS variables and we can use them everywhere in our CSS.

.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 a span to avoid that the gradient appears above it
  2. Start with a width and height of 0px and bring it up to 400px when the user hovers the button. And don’t forget to set a transition to make it appear with a swoosh 💨
  3. Use the coordinates to follow the mouse
  4. Apply a radial-gradient to the background and use a closest-side circle. Closest-side fills the whole before without getting beyond it.

Demo

See the Pen Mouse movement button with border-radius by Tobias Reich (@electerious) on CodePen.

CodeTea

A Nice collection of often useful examples done in HTML JavaScript CSS.

Read More