CSS trick to add border to a element on hover without pushing the contents

Hi, learned a CSS trick to avoid shaking/pushing of DOM elements when border is applied on hover.

Pushing of DOM elements when adding border on hovering.

As you can observe in the above image a border has been applied on hover over the li elements which causes pushing of other elements.

<!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;
        display: flex;
        justify-content: center;
    }
    ul li { 
        float: left;
        margin: 10px;
        background: aliceblue;
        width: 200px;
        height: 200px;
    }
    ul li span {
        font-size: 34px;
        line-height: 36px;
        text-align: center;
    }
    ul li:hover {
        border: 5px solid #333333; //(1)
        overflow: hidden;        
    }
</style>
</head>
<body>
    <ul>
        <li><span>1</span></li>
        <li><span>2</span></li>
        <li><span>3</span></li>
        <li><span>4</span></li>
    </ul>
</body>
</html>

Above is sample HTML code containing list of li elements.

As denoted by the number (1) in the code, on hover of li element border has been applied with width 5px , type solid and a color. This causes other elements to shake or get pushed.

To overcome this issue, we need to add the CSS “border: 5px solid transparent” to the li element. The ‘transparent’ property is needed when we don’t want border on normal view unless hovered.

<!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;
        display: flex;
        justify-content: center;
    }
    ul li { 
        float: left;
        margin: 10px;
        background: aliceblue;
        width: 200px;
        height: 200px;
        border: 5px solid transparent // (2)
    }
    ul li span {
        font-size: 34px;
        line-height: 36px;
        text-align: center;
    }
    ul li:hover {
        border: 5px solid #333333;
        overflow: hidden;        
    }
</style>
</head>
<body>
    <ul>
        <li><span>1</span></li>
        <li><span>2</span></li>
        <li><span>3</span></li>
        <li><span>4</span></li>
    </ul>
</body>
</html>

As denoted by the number (2) in the code block, we need to add transparent border to normal li element without hover, which will avoid shaking or pushing of other elements.

Effect after adding transparent border.

One thing to keep in mind is the border-width should be same in both normal and hovering, say 5px in the above code block, if there is difference in border width the issue will not get resolved. Hope it helps. Let me know if there is any other methods to solve this issue in comments.