Open In App

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

Last Updated : 10 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Adding a border to an element on mouse hover using CSS involves changing the element’s border style when the mouse pointer is over it. This effect enhances user interaction by visually highlighting the element, achieved using the :hover pseudo-class to modify border properties.

Approach

  • HTML Structure: Select the HTML element you want to apply the hover border effect to.
  • Initial Styling: Define the element’s default border properties using CSS for its normal state.
  • Hover Selector: Use the :hover pseudo-class to target the element when the mouse pointer is over it.
  • Modify Border: Change border attributes like width, style, or color within the :hover selector.
  • Smooth Transition: Add the transition property to ensure border changes occur smoothly on hover.

Example:  Here we are following above-explained approach.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" 
          content="width=device-width, initial-scale=1.0">

    <style>
        #container {

            /* Using the grid property */
            display: grid;
            grid-template-columns: 1fr 1fr 1fr 1fr;

            /* Making equal spaced divs */
            gap: 1rem;
        }

        .box {
            border: 4px solid black;
            background-color: red;
            height: 30vh;
        }
    </style>
</head>

<body>
    <div id="container">
        <div class="box">Box1</div>
        <div class="box">Box2</div>
        <div class="box">Box3</div>
        <div class="box">Box4</div>
    </div>
</body>

</html>

Output:

Supported Browsers:

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

 

 



Next Article

Similar Reads