WEB TUTORIALS
PRACTICE EXAMPLES
HTML REFERENCES
CSS REFERENCES
PHP REFERENCES
SPONSORED LINKS
Advertisements

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

Topic: HTML / CSSPrev|Next

Answer: Use the negative CSS margin

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

Let's try out an example to understand how it basically works:

  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  • <meta charset="utf-8">
  • <title>Add CSS Border on Hover without Moving the Elements</title>
  • <style>
  •     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:

Advertisements

Your Feedback:

We would love to hear from you, please drop us a line.