DEV Community

Nazanin Ashrafi
Nazanin Ashrafi

Posted on • Edited on

How to stop a link/button from moving on hover

Has it ever happen to you that you wanted to make hover effects and then everything is completely ruined ?
Like when you want to add background color and make the link/button bigger but then when you hover on it , it moves!

Let me show you an example of the messy hover effect :
Just hover on the twitter link and see what happens!




So what happened here??
I gave the hover effect 20px padding and when you hover on the link it expands/moves.

 a {
  color: #2196F3;
 }
Enter fullscreen mode Exit fullscreen mode
a:hover {
  background-color: #2196F3;
  color: white;
  border-radius: 15px;
  padding: 20px;
}
Enter fullscreen mode Exit fullscreen mode

Too annoying, right?


Now how should we fix this?
Actually it's easier than you think!
The trick is you need to create the effect BEFORE creating the hover effect. In other words it needs to exist before the hover effect has been created.


Let me show you :

In order to fix this mess all I had to do was create padding for the link and set the background color to transparent :

 a {
  color: #2196F3;
  padding: 20px;
  background-color: transparent;
 }
Enter fullscreen mode Exit fullscreen mode



I put the messy one and the fixed one in the same link to make things clearer.
You can play around with it on codepen to understand it better.

Top comments (8)

Collapse
 
daxlooopy profile image
Abdulaziz Sadi

Thanks for sharing

Collapse
 
otipip90 profile image
otipip90

Thanks a lot

Collapse
 
madhushreekunder profile image
Madhushree Kunder

Thanks you!

Collapse
 
madhushreekunder profile image
Madhushree Kunder

Thanks!

Collapse
 
ritvikdubey27 profile image
Ritvik Dubey

Great read thanks for sharing 🙌😃

Collapse
 
bangsofine profile image
bangsofine

thank you. i was having trouble applying border bottom on hover. you inspired me to have transparent border bottom first then change the color on hover. thanks for sharing

Collapse
 
asta profile image
Giorgi Kalatozishvili

thanks bro, u saved my ass

Collapse
 
hbandeira profile image
Henrique Bandeira

I've created a profile on dev.to just to say thanks. It worked out well!