How to apply border to an element on mouse hover without affecting the layout in CSS

Topic: HTML / CSS« Prev|Next »

Answer: Use the negative CSS margin

By default if you apply the border around an element on mouse hover it will move the surrounding elements from its original position. However using the negative CSS margin value and a little trick you can do it nicely without affecting the other elements or content.

  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  • <title>Add CSS Border on Hover without Moving the Elements</title>
  • <style type="text/css">
  •     ul {
  •         padding: 0;
  •         list-style: none;
  •     }
  •     ul li { 
  •         float: left;
  •         margin: 10px;
  •     }
  •     ul li a, ul li a img {
  •         display: block;
  •     }
  •     ul li a:hover {
  •         border: 5px solid #333333;
  •         overflow: hidden;        
  •     }
  •     ul li a:hover img{
  •         margin: -5px;
  •     }
  • </style>
  • </head>
  • <body>
  •     <ul>
  •         <li><a href="#"><img src="club.jpg" alt="Club Card"></a></li>
  •         <li><a href="#"><img src="diamond.jpg" alt="Diamond Card"></a></li>
  •         <li><a href="#"><img src="spade.jpg" alt="Spade Card"></a></li>
  •         <li><a href="#"><img src="heart.jpg" alt="Heart Card"></a></li>
  •     </ul>
  • </body>
  • </html>

Related FAQ

Here are some more FAQ related to this topic:

 
Close

Your Feedback:

 

We would love to hear from you! Please say something.