将固定网格重新制作为响应网格

时间:2013-09-20 11:16:47

标签: javascript jquery css grid responsive-design

我已经实现了这个固定网格:http://jsfiddle.net/challenger/UxzCa/1。有两个要求:

  • 图片应该适合 square card div(宽度/高度可以不同);
  • 不应修复卡片尺寸。

对于尺寸,可以使用jquery实现并重新计算window.resize事件的宽度/高度。有替代方法吗?

1 个答案:

答案 0 :(得分:1)

我有一个部分解决方案,负责处理图像宽高比问题和固定宽度问题。

对于网格的固定宽度,设置width: auto,这将允许浮动 根据需要包装到尽可能多的行:

.grid-row {
    width: auto;
    margin: 0 auto;
}

如果图像是纵向(高度/宽度> 1),则图像需要按高度缩放;如果是横向图像(高度/宽度<1),则需要缩放图像。

定义以下类:

.table-cell img.portrait {
    height: 100%;
}
.table-cell img.landscape {
    width: 100%;
}

然后使用以下jQuery方法根据每个图像的宽高比设置正确的类:

$('.table-cell').each(function(){
    var image = $(this).find('img');
    aspectRatio = image.height()/image.width();
    if (aspectRatio > 1) 
    {
        image.addClass('portrait');
    }
    else
    {
        image.addClass('landscape');
    }
});

<强> See Demo Fiddle

脚注

有可能使.card元素响应并使用类似于以下问题中提供的CSS技术保持其宽高比:

How do you vertically center absolute positioned text w/o declaring container size and w/o JS?

相关问题