javascriptcssgrid-layoutcss-grid

CSS grid layout changing column width with javascript


I try setting up a CSS grid layout as follows

.wrapper {
  width: 800px;
  display: grid;
  grid-template-columns: repeat(3, 200px);
  grid-template-rows: repeat(5, 200px);
}

Is it possible to locate grid-template-columns in JS then re-size the columns? I came across a situation where I could find it (lost the code) but when I tried changing it, Chrome DevTools say the value is computed and cannot be changed.

Any help pointing me in the right direction (or other ways to do it, but use of grid is a must) is highly appreciated.

Thanks.


Solution

  • @MikeC, if you're not opposed to using jQuery, you can change the column width using jQuery's .css() function, which

    Get the value of a computed style property for the first element in the set of matched elements or set one or more CSS properties for every matched element.

    You can read more on it in jQuery's documentation for the function here.

    Also, just so you can see it in action, I put together a codeply project that you can see it in action. If you click anywhere on the grid, it will resize (only once though). It's a primitive example.

    Here's the jQuery code it uses.

    $( "#grid" ).one( "click", function() {
      $( this ).css( "grid-template-columns", "repeat(2, 400px)" );
    });