$(()=>{
// get the card dom elements
var cardArray = Array.from($('.cards-group').find('.card'));
// get width of the card container / parent div
var innerWidth = $('.cards-group').width();
// get the cumulative height for all the cards
var cardArrayHeight=0;
cardArray.map((card)=>{ cardArrayHeight += $(card).height() });
// your custom number of columns (which you could data-tag to parent div)
let colNumber = 3 // change to suit tastes
// your custom card gap (which you could data-tag to parent div)
let colGap = 16 //= 1 rem default for html/body // change to suit tastes
// card width is the based on column numbers, less a column gap
var cardWidth = (innerWidth / colNumber) - colGap
// the total cumulative height is the height of all the cards, plus all the gaps except one gap (don't include a gap at the end)
var layoutTotalCardHeight = cardArrayHeight + ((cardArray.length-1) * colGap)
// the container height, will be a gross down of the height to fit into the number of columns, LESS the gaps at the bottom of each folumn
var containerHeight = (layoutTotalCardHeight / (1+ (1/colNumber))) - (colNumber * colGap)
$('.cards-group').height(containerHeight);
$('.cards-group').css('gap',colGap);
$('.cards-group .card').css('width',cardWidth);
})
5条答案
按热度按时间cetgtptt1#
正如Bootstrap 5文档中所解释的那样,Masonry JS插件是这种类型的“Pinterest”布局的推荐选项。Bootstrap 4中使用的多列卡片布局(card-columns)在Bootstrap 5中不再可用。
使用Masonry插件很容易。只需使用适当的
col-*
类设置跨列数,然后在包含row
的data-masonry
上设置data-masonry
属性。https://codeply.com/p/yrjCBwUeKR
grid-template-rows: masonry;
)选项目前只适用于Firefox,还不是推荐选项。y0u0uwnf2#
不要使用Bootstrap。使用CSS网格功能它可以帮助你通过循环,如果动态内容加载以及非常容易设置。
rseugnpd3#
0x6upsns4#
解决方案前的要点。上面提到的Moz网格模板不堆叠div。他们仍然在一个网格中。检查链路
https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_grid_layout/Masonry_layout#masonry_layout_with_spanning_items
如果你有一定数量的项目,并且不需要无限滚动或A-Z排序,那么就不需要外部库。
!注意:这种方法的缺点是卡片的顺序是A-Z向下每列然后交叉,而不是A-Z跨页和向下。这意味着最后一项可以出现在第一行第三列中。
然而,它真的很简单,不需要外部库--如果你想用一点数学和逻辑来找出自己的方法。在这里.
逻辑将所有卡片放入带有flex-wrap的d-flex列中,然后只需几行JavaScript或jquery即可根据卡片的总高度和宽度更改容器高度,这会导致列溢出 Package ,从而生成不会溢出并且底部合理齐平的列。
逻辑示例即。伪码
实际代码示例
HTML
Jquery/JavaScript
剥香蕉皮的方法永远不止一种。
icomxhvb5#
您要实现的是所谓的砌体布局。有不同的方法可以做到这一点,使用CSS网格,Flexbox或CSS的列功能。有关css-tricks.com方法的详细信息,请访问www.example.com上的this link。