Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
748 views
in Technique[技术] by (71.8m points)

html - :hover on a div with a border radius

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

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

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...