0

I have a div,I need to show this div on the center of the screen (ie viewable area) even while the user scrolled through the page.

so its style should be (for example)

{position:fixed; top:90px; left:150 px; z-index:9999; overflow:hidden;}

Now i need to find the value of left and top, so that the div will place in the center of the screen (ie viewable area), for any page .

How can i find the value of left & top with a javascript or jquery ?

Linto
  • 1,234
  • 3
  • 25
  • 41

6 Answers6

5

left:50%; top:50%; puts you in the middle, then you apply a fixed width and height and set margin-top and margin-left to negative a half of that width and height.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
2

In order to center something with fixed positioning then you will need to know the height and width of the element.

You then just need to margin-top and margin-left to negative half of the width and height in order to center it.

E.g. this class would center and element that has 100px height and 200px width.

.centered {
  position: fixed;
  top: 50%;
  left: 50%;
  margin-top: -50px;
  margin-left: -100px;
}

http://css-tricks.com/quick-css-trick-how-to-center-an-object-exactly-in-the-center/

Update: If you don't know the height and width of the element that needs to be centered ahead of page load then you'll need to use JavaScript to detect the size.

Here's a working example of how this can be done - http://jsfiddle.net/3Ag97/1/

tommarshall
  • 2,038
  • 5
  • 23
  • 36
0

You can use the flexbox module, although it's not widely supported yet: http://jsfiddle.net/b7nrS/.

.container {
  display: flex;
  align-items: center;
  justify-content: center;
}
pimvdb
  • 151,816
  • 78
  • 307
  • 352
0

Try this:

var $box = $('#box');

var bw = $box.width() / 2;
var bh = $box.height() / 2;

var wh = $(window).height() / 2;
var ww = $(window).width() / 2;

$box.css({'left': ww-bw, "top": wh-bh})

http://jsfiddle.net/mqMwj/

Ram
  • 143,282
  • 16
  • 168
  • 197
0
function centerObject(selector) {
var x = $(window).height() - $(selector).height();
var y = $(window).width() - $(selector).width();
$(selector).css("left", y / 2).css("top", x / 2);
};
Silviu Burcea
  • 5,103
  • 1
  • 29
  • 43
0
#divX {
    position: fixed; 
    left: 50%; 
    top: 50%; 
    width: 100px; 
    height: 100px; 
    margin-left: -50px; 
    margin-top: -50px; 
    background-color: #0000FF;
}
Gordon Bell
  • 13,337
  • 3
  • 45
  • 64