简体   繁体   English

CSS-通过父高度/宽度限制元素位置以防止溢出

[英]CSS - Limit element position by the parent height/width to prevent overflow

Is there a way to prevent an absolute positioned element to overflow its parent container by limiting its position if it overflows the parent? 有没有一种方法可以防止绝对定位的元素在溢出父容器时通过限制其位置来溢出其父容器?

In my case: I have a round graph, with bubbles inside, I use border-radius to create the circle, and use position:absolute + top and left to position the element based on a calculation result. 在我的情况下:我有一个圆形图形,里面有气泡,我使用border-radius来创建圆,并使用position:absolute + top and left根据计算结果定位元素。

I want to prevent this from happening: 我想防止这种情况的发生:

圈

In this case, or in an extreme case like top: 0; left: 0; 在这种情况下,或者在诸如top: 0; left: 0;的极端情况下top: 0; left: 0; top: 0; left: 0; the bubble overflows the parent circle, and I want it to be contained within the circle limits. 气泡溢出了父圆,我希望将其包含在圆限制内。

Is it possible to do that? 有可能这样做吗? Or do I have to use javascript? 还是我必须使用JavaScript? If I have to use javascript: is it possible to obtain the limit of an element rounded with border: radius: 100% ? 如果我必须使用javascript:是否有可能获得以border: radius: 100%取整的元素的限制border: radius: 100%

Not a perfect solution, but here's how overflow: hidden already has some built-in functionality for this. 这不是一个完美的解决方案,但是这里有overflow: hidden已经为此提供了一些内置功能。 I'm using JavaScript to have the dot follow the cursor: 我正在使用JavaScript使点跟随光标:

 $('.circle').on('mousemove', function(e) { $('.dot').css({ 'top': e.clientY, 'left': e.clientX }); }); 
 .circle { width: 180px; height: 180px; border: 5px solid black; border-radius: 50%; position: relative; overflow: hidden; } .dot { border-radius: 50%; background: red; width: 30px; height: 30px; margin-left: -30px; margin-top: -30px; position: absolute; pointer-events: none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="circle"> <div class="dot"></div> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM