How to Add a Border on Hover without Moving the Element in CSS?

If you apply a border around an element on mouse hover, the element moves, and therefore it pushes its surrounding elements away from their original position. This is the default behavior of HTML elements.

In CSS, there is no such direct property which can solve this problem. However, we can fix it very easily if we pay enough attention to the problem.

For example, when we put a border of 2px thickness around the element on hover, it pushes its surrounding elements 2px away from their original position.

So, if we anyhow pull the element 2px back on hovering, it will not affect the layout at all. Which we can do very easily with the help of negative margins.

For example, if you are applying a border of 2px thickness on hovering, apply a negative margin of -2px as well so that the total impact on the element becomes null.

See this working example:

Example:

div{
   background: yellow;
   padding: 10px;
}
div:hover{
   border: 2px solid red;
   margin: -2px;
}

Another Solution:

Another possible solution to this problem is to put a transparent border around the element which will be invisible until we hover over the element.

As soon as we hover over the element, we will set the color of the border so that it becomes visible.

Here is a working example:

Example:

div{
   background: yellow;
   padding: 10px;
   border: 2px solid transparent;
}
div:hover{
   border-color: red;
}

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.