Octavian
Octavian

Reputation: 4589

jQuery automatic div positioning on the center on the screen

I have this jQuery function:

    $(window).resize(function(){
  $('#modal').css({
    left: ($(window).width() - $('#modal').outerWidth())/2,
    top: ($(window).height() - $('#modal').outerHeight())/2
  });
});

This does what I need to: "places the div on the center of the screen on window resize". The only problem is that when I shrink the window enough (at 400-500px) or access the webpage from a low-resolution device (mobile phone), the heading gets out of the boundaries upside and you can't see it anymore.

Why this happens and how I can avoid that?

Upvotes: 1

Views: 5869

Answers (3)

nxtwrld
nxtwrld

Reputation: 2062

With a window smaller that than the modal, you are getting into negative values. The important thing is to think what is supposed to happen in that case. I usually stop positioning the window and make the modal cover the whole window: Using CSS media queries I alter the modal size from defined px value to match screen size relative value.

   #modal {
      width: 500px;
   }

    @media only screen and (max-width: 500px) {
      #modal { 
          width: 100%;
      }
    }

Upvotes: 0

Akhil Sekharan
Akhil Sekharan

Reputation: 12693

This function might help:

function setToCenterOfParent( obj, parentObj ) {
    var height = $( obj ).height();
    var width = $( obj ).width();
    if ( parentObj == window ) {
        $( obj ).css( 'top', ( $( parentObj ).height() / 2 ) - ( height / 2 ) );
        $( obj ).css( 'left', ( $( parentObj ).width() / 2 ) - ( width / 2 ) );
    }
    else {
        $( obj ).css( 'top', ( $( parentObj ).height() / 2 ) - ( height / 2 ) + $( parentObj ).position().top );
        $( obj ).css( 'left', ( $( parentObj ).width() / 2 ) - ( width / 2 ) + $( parentObj ).position().left );
    }
}

Upvotes: 1

Samuel Caillerie
Samuel Caillerie

Reputation: 8275

You can just add a small test :

$(window).resize(function(){
  var topPos = ($(window).height() - $('#modal').outerHeight())/2;

  $('#modal').css({
    left: ($(window).width() - $('#modal').outerWidth())/2,
    top: topPos > 0 ? topPos : 0
  });
});

Upvotes: 1

Related Questions