Open In App

How to add border to an element on mouse hover using CSS ?

Last Updated : 14 Dec, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

We have given a web page containing elements and the task is to add border to an element on mouse move over (hover) using CSS. When we add a border to an element on hovering the mouse, it affects the position of the other nearest element. To remove this problem, we can use the CSS margin property.

Example:   

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="utf-8">
  
    <title>
        Add CSS Border on Mouse Hover 
        without Pushing Content
    </title>
      
    <style>
        ul {
            padding: 0;
            list-style: none;
        }
  
        ul li {
            float: left;
            margin: 10px;
        }
  
        ul ul li {
            display: block;
        }
  
        ul li:hover {
            border: 5px solid green;
            overflow: hidden;
        }
  
        ul ul li:hover img {
            margin: -5px;
        }
    </style>
</head>
  
<body>
    <h2>GeeksForGeeks</h2>
      
    <h2>
        How to apply border to an element 
        on mouse hover without affecting 
        the layout in CSS?
    </h2>
      
    <ul>
        <li>Home</li>
        <li>news</li>
        <li>Images</li>
        <li>Music</li>
    </ul>
</body>
  
</html>


Output:

Supported Browsers:

  • Google Chrome
  • Internet Explorer
  • Firefox
  • Safari
  • Opera

 

 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads