0

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!

Maxiss
  • 986
  • 1
  • 16
  • 35
  • you can add class to columns and use `document.querySelectorAll('.your_column_class').length` – Harish Jun 03 '19 at 10:16
  • So you want to know how many div childs you have? – axel axel Jun 03 '19 at 10:17
  • duplicate of : https://stackoverflow.com/a/55243400/8620333 – Temani Afif Jun 03 '19 at 10:22
  • Thanks, this is for a mosaic gallery, I want to know how many columns I have in my responsive grid. if there is less than the good amount of items so that it makes a perfect square, I want the last row to be hidden. – Maxiss Jun 03 '19 at 11:29

2 Answers2

3

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

var columns = document.getElementsByClassName('box').length
virgiliogm
  • 946
  • 7
  • 15
1

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.

p4ttch
  • 41
  • 3