[英]CSS grid - count number of columns (javascript)
I have a CSS grid 我有一个CSS网格
.wrapper {
display: grid;
grid-template-columns: repeat(auto-fill, 12.5vw );
grid-template-rows: repeat(auto-fill, 12.5vw );
background-color: black;
grid-auto-flow: row dense;
color: #444;
}
<div class="wrapper">
<div class="box wide tall a">
</div>
<div class="box b">
</div>
<div class="box c">
</div>
<div class="box c">
</div>
<div class="box d">
</div>
<div class="box e">
</div>
<div class="box f">
</div>
<div class="box g">
</div>
<div class="box h">
</div>
</div>
And I would like to know the number of columns in my javascript code. 我想知道我的JavaScript代码中的列数。 is it possible?
可能吗?
EDIT: the reason i want this is that if there is less than the good amount of items so that it makes a square, I want these extra items not to be displayed at all. 编辑:我想要这的原因是,如果少于足够数量的项目,使它成为一个正方形,我希望这些额外的项目根本不显示。
Thanks a lot! 非常感谢!
您可以使用getElementsByClassName检索所有box div并获取数组长度:
var columns = document.getElementsByClassName('box').length
I think you are missing the minmax part of the grid-template-columns:
eg grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
我认为您错过了
grid-template-columns:
的minmax部分grid-template-columns:
例如grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
with out it, you will always have 7 columns, and the grid columns wont be responsive and change as page width shrinks/expands. 如果没有它,您将始终有7列,并且网格列将不会响应,并且不会随着页面宽度的缩小/扩展而变化。
can see Jen Simmons example page here : Spice Gallery Layout 可以在此处查看Jen Simmons示例页面: Spice Gallery布局
A Solution that doesnt require any javascript.. but a few media queries.. is to wrap your .wrapper div with a container. 一种不需要任何javascript ..但需要一些媒体查询的解决方案是用容器包装.wrapper div。 and set a max height.
并设置最大高度。 per screen break point when every there would be un even images on the last row.
每个屏幕的断点,当最后一行上的每个图像都没有偶数时。 then set the .container overflow-y:hidden;
然后设置.containeroverflow-y:hidden;
link to pen here : Hide last row of grid with css 在此处链接到笔: 用CSS隐藏网格的最后一行
Doing this with javascript you would need to know how many images you have, and what your minmax column widths are. 使用javascript进行此操作,您将需要知道有多少张图片以及minmax列的宽度是多少。 vw units are basicaly width in %.
大众单位基本上是宽度(%)。 so you would need to do some maths.
所以你需要做一些数学。 with a mod function to know how many items are on the last row.
使用mod函数可以知道最后一行有多少个项目。 and then need a way to hide them.
然后需要一种隐藏它们的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.