I've开发者_运维知识库 got an ASP.NET page with a master page, which for whatever reason causes top:0; left:0
to be just under the master page. Inspecting my generated DOM, I've found that <body>
is at the very top of the page, where I need to position the <div>
. How can I use JQuery to position my <div>
at the exact same location as my <body>
tag?
The reason that top:0
would not actually be the top is that the div must be contained within an element which has position: relative
or position: absolute
(more likely, relative).
The easiest way to fix this would be to append the div directly to the body.
$("#yourdiv").appendTo("body");
$("div").css($("body").offset());
Did you try this in your CSS?
html, body {
margin: 0;
padding: 0;
}
Use .offset()
:
$("#myDiv").offset({ top: 0, left: 0 });
Your div is being positioned relative to its closest ancestor with position: relative
or position: absolute
. In order to position it relative to the page, you need to compute the total offset and apply that to your div. .offset()
does all that for you.
Here's a demo illustrating what is going on: http://jsfiddle.net/gilly3/trSkC/
精彩评论