JSFiddle - React, Tailwind, and code Playground

by Soundar Pandian

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

var $element = $('.element');

    center();

    $(window).on('resize', function() {
        center();
    });

    function center() {
        var width = $element.outerWidth(true);
        var height = $element.outerHeight(true);

        console.log(width);
        console.log(height);

        $element
            .stop(true)
            .css({
                top: Math.max(0, ($(window).height() - height) / 2),
                left: Math.max(0, ($(window).width() - width) / 2)
            });
    }