简体   繁体   中英

CSS grid - count number of columns (javascript)

I have a CSS grid

.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. 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));

with out it, you will always have 7 columns, and the grid columns wont be responsive and change as page width shrinks/expands.

can see Jen Simmons example page here : Spice Gallery Layout

A Solution that doesnt require any javascript.. but a few media queries.. is to wrap your .wrapper div with a container. 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;

link to pen here : Hide last row of grid with css

Doing this with javascript you would need to know how many images you have, and what your minmax column widths are. 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. and then need a way to hide them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM