jQuery: Center fancybox in viewport

2019-05-11 15:36发布

问题:

I am currently using fancybox version 2 to display my images when a thumbnail is clicked but I can't seem to get the fancybox to sit in the middle of the viewport, vertically speaking, since horizontally it's fine.

I've tried quite a few things and this is the latest:

CSS

.fancybox-wrap { 
    position: fixed !important;
    top: 50px !important;
} 

jQuery

jQuery(document).ready(function() {
    $(".fancybox-wrap").css("position", "absolute");

    // fancybox initialisation etc

});


$(window).scroll(function() {
    $('.fancybox-wrap').css('top', $(this).scrollTop() + "50px");
});

Does anyone have any ideas?

回答1:

$(window).bind('resize', function() {
    var top = ($(window).height() / 2) - ($(".fancybox-wrap").outerHeight() / 2);
    var left = ($(window).width() / 2) - ($(".fancybox-wrap").outerWidth() / 2);
    $(".fancybox-wrap").css({ top: top, left: left});
}).trigger('resize');

http://jsfiddle.net/aGhxK/23/



回答2:

The only thing you need to do is add to website css

html, body {height: 100%;}

And fancybox will position image at the screen center instead of page center.



回答3:

This sets left and top using position: absolute dinamically:

http://jsfiddle.net/aGhxK/1/