JSFiddle - React, Tailwind, and code Playground
HTML
<div class="element">
<p>I want to center this element vertically and horizontally.</p>
</div>
CSS
.element
{
background: #eee;
border: 1px solid #ccc;
font-size: 24px;
margin: 10px;
padding: 20px;
position: absolute;
}
JavaScript
jQuery(document).ready(function() {
center();
});
jQuery(window).resize(function(){
center();
});
function center() {
var $element = $('.element');
var width = $element.outerWidth(true);
var height = $element.outerHeight(true);
console.log(width);
console.log(height);
$element
.stop(true)
.animate({
top: Math.max(0, ($(window).height() - height) / 2),
left: Math.max(0, ($(window).width() - width) / 2)
});
}