Syamsul 'isul' Arifin

kartunis dan desainer

Mon, Apr 25, 2022

CSS Grid (Plus JS) with Square Images


CSS Grid is an awesome feature from CSS3. I prefer use it than CSS Flex. But sometimes we need little help from javascript. One of them is when we need to make gallery with square images. And of course… responsive. You can watch the demo.


<div class="container">
        <a href="img/ing-5WA3wX3zaHY-unsplash.jpg">
            <img src="img/ing-5WA3wX3zaHY-unsplash.jpg" alt="">
        <a href="img/gabriella-clare-marino-ELvWCtOvl4U-unsplash.jpg">
            <img src="img/gabriella-clare-marino-ELvWCtOvl4U-unsplash.jpg" alt="">
        <a href="img/yousef-espanioly-jtKlXesSCro-unsplash.jpg">
            <img src="img/yousef-espanioly-jtKlXesSCro-unsplash.jpg" alt="">
        <a href="img/charleen-vesin-vjFcom_lbs0-unsplash.jpg">
            <img src="img/charleen-vesin-vjFcom_lbs0-unsplash.jpg" alt="">
        <a href="img/nancy-hughes-RVop5szR6EM-unsplash.jpg">
            <img src="img/nancy-hughes-RVop5szR6EM-unsplash.jpg" alt="">
        <a href="img/safaa-sumery-5qxYYZlUo6M-unsplash.jpg">
            <img src="img/safaa-sumery-5qxYYZlUo6M-unsplash.jpg" alt="">


* {
    box-sizing: border-box;

body {
    padding: 0;
    margin: 0;

img {
    width: 100%;
    height: auto;

.container {
    max-width: 700px;
    margin-left: auto;    
    margin-right: auto;
    margin-top: 50px;
    margin-bottom: 100px;
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    -moz-column-gap: 10px;
         column-gap: 10px;
    row-gap: 10px;

.container a img {
    -o-object-fit: cover;
       object-fit: cover;
    display: block;

We use resize events in JS to keep the images responsive. We must get the container grid width, not the item grid cause just the container grid gave responsive value in the log when I run mobile mode on the browser.


let container = document.querySelector('.container');
let imgItem = document.querySelectorAll('.container a img')
let column = 3; 
let columnSum = 20;

window.addEventListener('load', function(){    
    let itemLoad = Number((container.clientWidth - columnSum) / column);      
    for (let i = 0; i < imgItem.length; i++){
        imgItem[i].style.width = itemLoad + 'px';
        imgItem[i].style.height = itemLoad + 'px'

window.addEventListener('resize', function(){
    let itemRes = Number((container.clientWidth - columnSum) / column); 
    for (let i = 0; i < imgItem.length; i++){
        imgItem[i].style.width = itemRes + 'px';
        imgItem[i].style.height = itemRes + 'px'
comments powered by Disqus