jQuery: Center fancybox in viewport

2019-05-11 15:32发布

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?

3条回答
贪生不怕死
2楼-- · 2019-05-11 16:04

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楼-- · 2019-05-11 16:13
$(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/

查看更多
成全新的幸福
4楼-- · 2019-05-11 16:22

This sets left and top using position: absolute dinamically:

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

查看更多
登录 后发表回答