正方形空间灯箱图像定心



Squarespace如何将每个图像居中,即使它们在风景和肖像图像之间有不同的尺寸变化?

我一整天都在尝试不同的解决方法,但似乎还是没有找到。

http://bryant-demo.squarespace.com

看看他们的灯箱和代码。

不知道他们做什么,因为我可以看到他们得到图像尺寸和许多其他的东西作为属性…但这里有一个简单的定心方法,与屏幕尺寸有关,这是基本的计算,我猜在他们的例子中也应用了。此外,还有不同的css方法来居中…

 screen_width=$(window).width();
        screen_height=$(window).height();
        img_width= $('#images img').eq(i).width();
         img_height= $('#images img').eq(i).height();
        //set to center
        $('#images img').eq(i).css('margin-top',(screen_height-img_height)/2+'px');
         $('#images img').eq(i).css('margin-left',(screen_width-img_width)/2+'px');

演示:http://jsfiddle.net/dfwosy4m/

注:如果你将图像设置在其他容器中,而不是body中,你只需要对不同的元素应用相同的计算。

编辑:

实际上,同样的方法工作,当然,无论容器是大的,或小于图像…所以,简单的:image center = container center,剩下的用overflow:hidden

function centralize() {
    screen_width = $('.box').width();
    screen_height = $('.box').height();
    $('#images img').each(function(i) {
        img_width = $(this).width();
        img_height = $(this).height();
        //set to center
        $(this).css('margin-top', (screen_height - img_height) / 2 + 'px');
        $(this).css('margin-left', (screen_width - img_width) / 2 + 'px');
});
}
    centralize();

新演示:

http://jsfiddle.net/dfwosy4m/3/

注:检查页面上的元素,在我的演示中,你将看到同样的技术被使用(隐藏的图像部分将由检查器显示)…关键是溢出:隐藏为固定的盒子,所以…您应该应用类似的CSS来获得所需的效果。

最新更新