:将鼠标悬停在具有边框半径的div上

Jac*_*don 6 html css border css3

我有悬停问题和边界半径的div.

当div内部有图像和边框半径时,它的"hitbox"不正确.将鼠标悬停在div的任何角上(如果没有边框半径,角落将会是这样)会导致悬停样式显示.我希望样式只显示鼠标实际上在圆圈内.

如果div中没有​​任何内容,则div的"hitbox"是正确的,但是当其中有元素时它超过边界.

我可以在div中使用背景图像,但是我不希望出于可访问性原因.

#test-wrapper {
  background-color: #EEE;
  border: 4px dashed #999;
  display: inline-block;
}

#switcher {
  border-radius: 50%;
  overflow: hidden;
  position: relative;
}

#switcher,
#switcher .first,
#switcher .second {
  width: 100px;
  height: 100px;
}

#switcher .first,
#switcher .second {
  position: absolute;
  top: 0;
  left: 0;
}

#switcher:hover .first {
  display: none;
}
Run Code Online (Sandbox Code Playgroud)
  <!-- This is used to show the "hitbox" for the switcher and has no effect on the switcher itself -->
<div id="test-wrapper">
  <div id="switcher">
    <!-- Shown on hover -->
    <img src="https://placeholdit.imgix.net/~text?txtsize=30&txt=Second&w=100&h=100&txttrack=0" class="second">
    
    <!-- Always shown -->
    <img src="https://placeholdit.imgix.net/~text?txtsize=30&txt=First&w=100&h=100&txttrack=0" class="first">
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

Sha*_*ggy 12

这里的问题是子元素不会继承border-radius父元素.有两种方法可以实现您想要的:您可以设置border-radius要匹配的子元素或大于父元素的半径,或者设置父元素的overflow属性hidden.

这是一个快速的片段,说明了问题和两个解决方案:

*{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;
}
Run Code Online (Sandbox Code Playgroud)
<div><p>Square hit area</p></div><div><p>Round hit area 1</p></div><div><p>Round hit area 2</p></div>
Run Code Online (Sandbox Code Playgroud)


如果子元素是图像,那么您将需要使用图像映射来裁剪其命中区域的附加技巧(信用:边界半径和:悬停状态区域问题),如下所示:

*{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;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)