How center modal dialog in scrolled window with position absolute?

32,741

Solution 1

You should use

position:fixed

instead absolute/relative.

position:fixed The element is positioned relative to the browser window.

Use this and you should not face any issues due to scrolling.

http://www.w3schools.com/cssref/pr_class_position.asp

You can see this topics, too:

Fixed Positioning without Scrolling

How to place a div center of the window after scrolling

Solution 2

So your dialog has its position set to absolute and it is an immediate child of the document/body, right !?

Centering a prompted modal with absolute position:

// Get the document offset :
var offset = $(document).scrollTop(),

// Get the window viewport height
viewportHeight = $(window).height(),

// cache your dialog element
   $myDialog = $('#MY_DIALOG');

// now set your dialog position
$myDialog.css('top',  (offset  + (viewportHeight/2)) - ($myDialog.outerHeight()/2));

Solution 3

If it is inside of a scrollable div, make sure that original div is: <div style="position:relative;">.

That way, a div inside it that is absolute will stay within the confines of it, and use its parent relative div as a reference point for top:50%;

Solution 4

In general, to find the center of the viewport with scroll bars. Take window height, divided by 2, plus scroll top. Result is the number of pixles that something should be offset from the document top.

If your positioned element is a child of more than one scrollable element then you will need to account for those, but the basic math is the same.

As a side note, an example of the markup you are trying to use would help get more exact answers.

Share:
32,741
paganotti
Author by

paganotti

Updated on August 18, 2020

Comments

  • paganotti
    paganotti over 3 years

    I'm trying to center a modal dialog in scrolled window. This modal are position absolute because must be draggable in screen. I use this plugin for draggable function:

    http://threedubmedia.com/code/event/drag

    My problem is that this modal has position absolute if I put top: 50% it display modal in center window but not considering all scrolled window.