Search code examples
javascripthtmlcsspositionwindow

Javascript window positioning


I have this javascript social locker that works inside a window and I am having trouble when testing it on different screens for responsive (like mobile and etc) because the window changes position. So far I know that this part of the code affects the positioning but I don't know how.

This is the CSS:

 #gatewaydiv
    {
    max-width: 15em;
    height: 6em;
    padding: 9em;
    position: absolute;
    display:none;
    background-color:#0e0f0f;

    text-align:center;
    font-family:arial;
    font-weight:bold;
    opacity:0.9;
    margin: auto;
    margin-top: -10%;
 }

And this is the Javascript window:

function setupgateway()
{
var Left = $(window).width() /2.6;
Left = Left - $('#gatewaydiv').width() / 2;

var Top = $(window).height()/2;
Top = Top - $('#gatewaydiv').height()/6;

$('#gatewaydiv').css('top', Top+'px').css('left', Left+'px').css('display', 'inline');

If someone can please explain me how does this javascript window code behaves and how can I get it right to work on all devices?

I have read a lot of similar questions but haven't found my answer because the code is quite different, nor this is a pop-up window and I am no javascript expert, to be honest. You can see the live version here

Thank you!


Solution

  • You can make any element centered (Vertically and Horizontally) using below CSS. For example -

    #gatewaydiv{
        position:absolute;
        margin: auto;
        left: 0;
        right: 0;
        top: 50%;
        -moz-transform: translatey(-50%);
        -ms-transform: translatey(-50%);
        -o-transform: translatey(-50%);
        -webkit-transform: translatey(-50%);
        transform: translatey(-50%);
     }
    

    Remember, you'll have to remove margin-top:-10% and also disable/remove the Javascript.

    Also, replace this line -

    $('#gatewaydiv').css('top', Top+'px').css('left', Left+'px').css('display', 'inline');
    

    By this line -

    $('#gatewaydiv').css('display', 'inline');