Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 over any of the corners of the div (where the corners would be if it didn't have a border radius) causes the hover style to show. I would expect the style to only show when the mouse is actually within the circle.

If there is nothing in the div, the div's "hitbox" is correct, however it surpasses the border when there are elements within it.

I could a background image in the div, however I'd prefer not to for accessibility reasons.

#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;
}
  <!-- 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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
775 views
Welcome To Ask or Share your Answers For Others

1 Answer

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...