html:
<div id="container">
<div id="header">
<div id="animate">
cartagena
</div>
</div>
what I want to do is to move the "animated" div to the center using Jquery.
my current js:
$(document).ready(function() {
$("#animate").animate({left: "+=512"}, 2000);
});
and now I'd like to make it to the center instead of just 512 px to the right.
I am assuming that the position of #animate
is absolute
. To center the element in its parent element just add the half of its parent's width minus the half of its own width to left
:
$("#animate").animate({
left: $("#animate").parent().width() / 2 - $("#animate").width() / 2
}, 2000);
I created a demo using jsFiddle.
Asuming you want to center to window, use this code:
$("#myJQUIDialog").parent().position({
my: "center",
at: "center",
of: window,
using: function (pos, ext) {
$(this).animate({ top: pos.top }, 600);
}
});
This center the dialog, and animate at the same time, resulting in a smooth centering
You can use it this way to center it to the screen,
Jquery
$(document).ready(function() {
$("#animate").animate({left: $(window).width() / 2}, 2000);
});
css
<style type="text/css">
div
{
height: 50px; width: 50px; background-color: Red;position:absolute; top:0; left:0;
}
</style>
html
<div id="container">
<div id="header">
<div id="animate">
cartagena
</div>
</div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With