Maxiss
Maxiss

Reputation: 1056

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!

Upvotes: 0

Views: 3420

Answers (2)

p4ttch
p4ttch

Reputation: 41

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.

Upvotes: 1

virgiliogm
virgiliogm

Reputation: 976

You can use getElementsByClassName to retrieve all the box divs and get the array length:

var columns = document.getElementsByClassName('box').length

Upvotes: 3

Related Questions