CSS grid layout changing column width with javascript

15,339

@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)" );
});
Share:
15,339

Related videos on Youtube

MikeC
Author by

MikeC

Updated on June 04, 2022

Comments

  • MikeC
    MikeC almost 2 years

    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.

  • MikeC
    MikeC over 6 years
    Thank you for answering. jQ is not allowed for this. Possible with an answer in pure javascript? Thx!
  • MikeC
    MikeC over 6 years
    I could use document.getElementsByClassName('wrapper')[0].style.gridTemp‌​lateColumns to access something but it returns an empty string...
  • MikeC
    MikeC over 6 years
    OK got it! Seems that I can directly set the above variable and it'll change the width right away! Thanks for assistance!
  • BlessedKey
    BlessedKey about 5 years
    It appears this works in FireFox but not in Chrome yet. Chrome 73.0.3683.75 (Official Build) (64-bit) Firefox 65.0 (64-bit) you can check here : codepen.io/bileschi/pen/ZPRPqr