How to make mansory elements responsive yet take up all available space?

I am using mansory.js to layout my images and their details( all in a div class=”main-section”) , They all are contained in a div class=”main”, The problem I am facing is due to how the elements widths is being calculated, If i say columnWidth:300 It works fine, but when i resize the window only below 300, ( like i expand the window about 150px wider, ) the layout stays the same leaving 150px blank on the right hand side, I want the column width to be dynamic so that the width of the items adjusts and increases so that they all add up to 100% of the container,
I tried using a function for it, like to calculate the width but it acts weirdly, and stacks all images on top of each other,( kinda, i don’t get it it just gets messed up)

this js code, adds those white spaces on the right hand side,

`
var elem = document.getElementById('main');
var msnry = new Masonry(elem, {
    itemSelector: '.main-section',
    columnWidth: 300,
    isFitWidth:true,
    percentPosition: true,
    gutter: 16 // Spacing between items
});



document.addEventListener("DOMContentLoaded", function () {
    setTimeout(function() {
        msnry.layout();
    }, 350); 
});

window.addEventListener('resize', function() {
    setTimeout(function() {
        msnry.layout();
    }, 350); 
});`

this code does that jumbling of the items and messes up everythig

`....snry = new Masonry(elem, {
    itemSelector: '.main-section',
    columnWidth: function() {
        var elem = document.getElementById('main');
        var containerWidth = elem.offsetWidth;
        var numColumns = Math.floor(containerWidth / 300); 
        console.log( containerWidth / numColumns); 
        return 300;
    },
    isFitWidth:true,
    percent.....`

[as you can see i tried debugging using console log and just returning 300, but it doesn’t work, and displays nothing in console]

i attached the jumbled up image and the white space image with it too

white space on right
Weird image layout

also heres the css for container

`    #main-container{//this covers the main
        width: calc(100% - 160px);
        margin:0px 80px;
        margin-top: 40px;
    }
    #main{
        width: 100%;
    }
    .main-section{
        width: 300px;
        position: relative;
        transition: all 0.1s ease-out;
        background-color: white;
        box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.04);
        margin-bottom: 16px;
        border-radius: 16px;
    }
`