JSFiddle - React, Tailwind, and code Playground
HTML
<div class="block"></div>
CSS
*{margin: 0; padding: 0;}
html, body {
width: 100%;
height: 100%;
}
.block {
top: 0;
left: 0;
right: 0;
bottom: 0;
width: 200px;
height: 200px;
margin: auto;
position: absolute;
background-color: red;
}
.offset {
/* margin-left: 0; */
transition: 1s ease;
}
JavaScript
$(".block").click(function () {
var $this = $(this);
if($this.hasClass("offset"))
return toCenter($this);
toTop($this);
});
function toTop(elem) {
elem.css("margin-left", elem.offset().left);
elem.css("margin-top", elem.offset().top);
setTimeout(function () {
elem.addClass('offset');
elem.css("margin-left", 0);
elem.on("transitionend", function () {
elem.off("transitionend");
elem.css("margin-top", 0);
});
}, 0);
}
function toCenter(elem) {
var body = $(document.body),
toCenter,
halfWidth = (body.width() - elem.width()) / 2;
elem.css("margin-left", halfWidth);
elem.on("transitionend", function () {
if(!toCenter) {
var halfHeight = (body.height() - elem.height()) / 2;
elem.css("margin-top", halfHeight);
return toCenter = true;
}
elem.removeClass("offset");
elem.off("transitionend");
elem.css("margin-left", "");
elem.css("margin-top", "");
});
}