:hover on a div with a border radius

前端 未结 2 1398
暗喜
暗喜 2020-12-17 21:23

I\'m having an issue with hovering and a div with a border radius.

When a div has images inside it and a border radius, the \"hitbox\" for it is incorrect. Hovering

相关标签:
2条回答
  • 2020-12-17 21:52

    The problem here is that child elements do not inherit the border-radius of their parents. There are 2 ways to achieve what you want: you can either set the border-radius of the child element(s) to match or be greater than the parent element's radius or set the overflow property of the parent element to hidden.

    Here's a quick Snippet illustrating the problem and both solutions:

    *{box-sizing:border-box;color:#fff;font-family:arial;margin:0;padding:0;}
    div{
        background:#000;
        border-radius:50%;
        display:inline-block;
        line-height:150px;
        margin:10px;
        text-align:center;
        vertical-align:top;
        width:150px;
    }
    p{
        background:rgba(255,0,0,.25);
    }
    div:nth-of-type(2)>p{
        border-radius:50%;
    }
    div:nth-of-type(3){
        overflow:hidden;
    }
    <div><p>Square hit area</p></div><div><p>Round hit area 1</p></div><div><p>Round hit area 2</p></div>


    If the child elements are images then you'll need the added trick of using an image map to crop their hit areas (Credit: Border-radius and :hover state area issue), like so:

    *{box-sizing:border-box;color:#fff;font-family:arial;margin:0;padding:0;}
    div{
        background:#000;
        border-radius:50%;
        display:inline-block;
        margin:10px;
        text-align:center;
        vertical-align:top;
        width:calc(33% - 20px);
        max-width:600px;
    }
    img{
        display:block;
        cursor:pointer;
        height:auto;
        width:100%;
    }
    div:nth-of-type(2)>img{
        border-radius:50%;
    }
    div:nth-of-type(3){
        overflow:hidden;
    }
    <div><img alt="" height="600" src="http://lorempixel.com/600/600/nature/3/" width="600"></div><div><img alt="" height="600" src="http://lorempixel.com/600/600/nature/3/" width="600" usemap="circle"></div><div><img alt="" height="600" src="http://lorempixel.com/600/600/nature/3/" width="600" usemap="circle"></div>
    <map name="circle"><area shape="circle" coords="0,100%,100%,100%"></map>

    0 讨论(0)
  • 2020-12-17 22:12

    I've seemed to find a way around it, if the parent element has overflow hidden and you just the image z-index to -1 or something lower than the parent it also works. Don't know why though

    0 讨论(0)
提交回复
热议问题