css link element jumps on hover

2019-01-23 10:39发布

问题:

I am trying to put a border around a link on hover, and the style applies to it, but it jumps (the element jumps) when i hover over it... what can I do? code:

  .navigation li:hover {
   border: 1px solid #ccc;
 }

回答1:

You 'jump' is caused by the 1px height of the border, that make your li move

You might use

 .navigation li:hover {
   border-color: #ccc;
 }

 .navigation li {
   border: 1px solid #<parentBackgroundColor/transparent>;
 }

instead. This way, the border is here from the beginning, so no jump on hovering, and it's invisible, since it's the same color of the parent container or transparent.



回答2:

.navigation li {
    border: 1px solid transparent;
}

You can add a transparent border when you're not hovering, then it won't jump.

Or, you can remove a total of 2px vertical padding around the element, for example:

.navigation li {
    padding: 10px
}
.navigation li:hover {
    padding: 9px;
    border: 1px solid #ccc;
}