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,168
  • 3
  • 22
  • 40

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
  • 301,028
  • 70
  • 427
  • 540
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
  • 1,838
  • 3
  • 20
  • 34
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
  • 141,012
  • 68
  • 291
  • 345
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/

undefined
  • 136,817
  • 15
  • 158
  • 186
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
  • 4,573
  • 1
  • 24
  • 41
0
#divX {
    position: fixed; 
    left: 50%; 
    top: 50%; 
    width: 100px; 
    height: 100px; 
    margin-left: -50px; 
    margin-top: -50px; 
    background-color: #0000FF;
}
Gordon Bell
  • 12,283
  • 3
  • 41
  • 63