使 <div> 的边框与 .left 位置对齐

Making the border of a <div> aligned with the .left position

我的 Jquery 程序涉及制作边框以防止 div 从容器中退出。但是在execution(容器是白框)中,左边框比我容器的position().left 属性更靠左,右边框比[=13=更靠左]

会不会是我的html格式

造成的
<html>
    <body>
        <div class ="main">
            <div class = "container></div>
        </div>
    </body>
</html>

其中 main 的位置是 static,container 的位置是 absolute,并且 html 有 margin: 0; 关于如何使左侧位置与视觉左边框对齐有什么建议吗?

解决此问题的一种可能方法是计算 .main div 的位置和尺寸,然后将它们应用于其内容(.container div).我创建了一个函数来执行这些值的获取和设置。

所以,给定这样的结构:

  <div class="main">
    <div class="container">
    </div>
  </div>

其中我们假设.main是静态定位的,.container一定是绝对定位的;我们只需要使用 jQuery .offset() 函数来获取 .main 的位置,并使用 .width().height() 获取其维度。然后我们只需要设置 .container div 的确切值,我们可以通过使用 .css() 函数来实现。我将所有这些打包在一个名为 adaptToFrame():

的函数中
function adaptToFrame() {  
    /*We get the values*/
    var position_top = $(".main").offset().top;
    var position_left = $(".main").offset().left;  
    var width = $(".main").width();
    var height = $(".main").height(); 

    /*We set the values*/
    $(".container").css({"position": "absolute", "top": position_top, "left": position_left, "width": width, "height": height });   
}

adaptToFrame();

$(window).resize(function() {
    adaptToFrame();
});   

除了调用该函数外,我还在 $(window).resize 函数中再次调用了它:这样我们承认,如果最终调整浏览器 window 的大小,将重新计算并重新应用这些值(以防万一站点响应并且使用的单位不是绝对的)。

希望有用。