Change Border Size on Hover Without Parent or Child Content "Jumping"


/ Published in: CSS
Save to your folder(s)

Think this is a good one to remember.

Let's say you have a set of list items and all of them have a border of 1px. Inside you have an image.

When you hover over each list item you want the border to change thickness to 2px.

The trick is to reduce the width and height of the list item so, when you add the thickness of the border to it - its still the same size. So:-

Normal state: 84px + 2px border x 84px + 2px border= 86px x 86px
Hover state: 82px + 4px border x 82px + 4px border = 86px x 86px

Then to ensure the image inside the list item doesn't "jump", position it absolutely and use a negative margin.


Copy this code and paste it in your HTML
  1. <body>
  2.  
  3. <style>
  4. /* list item styles*/
  5. ul {width:500px;list-style-type:none;}
  6. ul li{float:left;margin-left:14px;height:86px;width:86px;}
  7. /* links */
  8. ul li a {display:block;width:84px;height:84px;border:1px solid #0033CC;color:#000;text-decoration:none;}
  9. ul li a img {width:84px;height:84px;display:block;position:relative;border:none;}
  10. /* hover state */
  11. ul li a:hover {border:2px solid #cc0000;width:82px;height:82px;position:relative;overflow:hidden;}
  12. ul li a:hover img {position:absolute;left:-1px;top:-1px;}
  13. </style>
  14.  
  15. <!-- html -->
  16. <ul id="my-list-items">
  17. <li>
  18. <a title="my-page.html" href="my-page.html">
  19. <img src="test.jpg"/>
  20. </a>
  21. </li>
  22. <li>
  23. <a title="my-page-2.html" href="my-page-2.html">
  24. <img src="test.jpg"/>
  25. </a>
  26. </li>
  27. </ul>
  28.  
  29. </body>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.