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
200 views
in Technique[技术] by (71.8m points)

html - CSS wrong appearance of border-radius on a nested div

Using the following HTML I need to:

  • Make sure that the border of target div (pink) is adjacent of the wrapper-target red border div.

  • Must work on any value of border-radius.

Considering that:

  • I am using box-sizing: border-box; but can be also reset to a default value.
  • I cannot change the border-radius property of the target div.

*,
*:after,
*:before {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}
<div id="wrapper-target" style="position:absolute;top:100px;left:100px;width:250px;height:250px;border-radius:50px;border:25px solid red;">
  <div id="target" style="position:relative;width:100%;height:100%;background-color:plum;border-radius:inherit">
  </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)

Part 1 of the problem: (Child becoming a round in original demo)

The problem is because of the box-sizing: border-box. When this is set, the defined height, width of the box (250 x 250px) is considered as inclusive of the width of the border and the padding. So, the element's actual content area is only 200px x 200px (excluding 50px for horizontal & vertical borders).

Thus the child div will only have a size of 200px x 200px (this can be verified in Dev tools). When a border-radius of 100px is inherited from parent, it becomes a round as that is half of its dimensions.

So, the border-radius cannot be inherited for the child if the shape has to be maintained. It should be set as 80px (approximate). (Initially I had mentioned that a value of 76px was working better and that I was trying to find out the reason for it - please refer to Part 2 for the reason.)

*,
*:after,
*:before {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}
<div id="wrapper-target"       
     style="position:absolute;
            top:100px;left:100px;
            width:250px;height:250px;
            border-radius:100px;
            border:25px solid red;">
  <div id="target" 
       style="position:relative;
              width:100%;height:100%;
              background-color:plum;
              border-radius:76px;">
  </div>
</div>

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

...