My Jquery program involves making borders to prevent exit of divs from the container. But in the execution (the container is the white box), the left border is further left than the position().left
property of my container and the right border is further left than $(".container").position().left()+$(".container").width()
Could this be caused by my basic html format of
<html>
<body>
<div class ="main">
<div class = "container></div>
</div>
</body>
</html>
where main's position is static
and container's position is absolute
and html has margin: 0;
Any suggestions on how to make the left position align with the visual left border?
A possible approach to solve this could be by calculating the position and the dimensions of the .main
div and then applying them to its content (the .container
div). I created a function that performs the getting and setting of those values.
So, given a structure like this:
<div class="main">
<div class="container">
</div>
</div>
in which we assume that .main
is static-positioned and .container
must be absolute-positioned; we just need to use the jQuery .offset()
function to get .main
's position, and also get its dimensions with .width()
and .height()
. Then we only need to set the .container
div the exact values, which we can achieve by using the .css()
function. I packaged all that in a function called 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();
});
Besides invoking the function, I called it again inside the$(window).resize
function: this way we grant that, given an eventual resizing of the browser's window, the values will be recalculated and reapplied (just in case the site being responsive and the units used are not absolute).
I hope it was useful.