Search code examples
htmlcsspseudo-elementborder-radius

Hover on before element with border radius is not working properly


Problem

Before element has a boeder-radius: 50% on it, but hovering over the rounded area still trigers hover event. Problem

Code

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        #test {
            height: 100px;
            width: 100px;
        }

        span {
            line-height: 100px;
            text-align: center;
            width: 100%;
            display: inline-block;
        }

        #test::before {
            position: absolute;
            content: "";
            background-color: red;
            width: 100px;
            height: 100px;
            display: inline-block;
            z-index: -1;
            border-radius: 50%;
        }

        #test:hover::before {
            background-color: blue;
        }
    </style>
</head>
<body>
    <div id="test">
        <span>Hi</span>
    </div>
</body>
</html>

Is there anyway to manipulate the box so it works like div with border radius? Thank you!


Solution

  • when you use border-radius does not mean the element will shrink to the border it is specified. it will still be a rectangle and catch events to its correct size

    Resolve:

    • if you want to change color only when hover on circle you need to use javascript to check mouse position
    • you can also use orthodox setting properties like clip-path it will tell the browser the actual shape of the element:
    #test {
      height: 100px;
      width: 100px;
      clip-path: circle(50% at 50% 50%);
    }