JSFiddle - React, Tailwind, and code Playground

by dnag

HTML

<div id="popup">This is some sample text, just a little bit of sample text.</div>
<div id="debug_output"></div>

CSS

body {
    background: #888;
}

#popup {
    background: #FFF;
    position: fixed;
    top: 50px;
    left: 0;
    border: 1px solid #000;
    box-shadow: 0 0 3px #CCC;
    padding: 10px;    
}

#debug_output {
    width: 150px;
    margin: 280px auto 0 auto;
}

JavaScript

function center_horizontally(id)
{
    var windowWidth = document.documentElement.clientWidth;
    var popupWidth = $(id).outerWidth();
    
    var new_left = Math.max(0, windowWidth/2 - popupWidth / 2);

    $('#debug_output').html('windowWidth: ' + windowWidth + '<br />popupWidth: ' + popupWidth);
    
    $(id).css('left', new_left + 'px');
}

$(function(){
    $(window).resize(function() {
        center_horizontally('#popup');
    });
    
    center_horizontally('#popup');
});