Duco
Duco

Reputation: 57

Javascript to set css properties grid-template-columns and grid-template-rows

I'm looking for an equivalent for grid-template-columns and grid-template-rows for javascript dom. I made a simple grid layout in html and css:

<div class="box">
    <div id="box1"><a href="#">box1</a></div>
    <div id="box2"><a href="#">box2</a></div>
    <div id="box3"><a href="#">box3</a></div>
    <div id="box4"><a href="#">box4</a></div>
</div>

.box {
    display: grid;  
    grid-template-columns: 33% auto;
    grid-template-rows: 350px 588px;
}

I want to edit the styling for grid-template-columns and grid-template-rows in javascript, but I found out javascript dom doesn't support this property. Is there any other way I can edit the boxes so I can change the size of them?

Thank you for helping.

Upvotes: 2

Views: 2447

Answers (1)

Mark
Mark

Reputation: 92461

You can use .style.gridTemplateColumns to alter the columns and .style.gridTemplateRows for the rows:

let a = true
setInterval(() => {
  let box = document.getElementById('box')
  box.style.gridTemplateColumns = a ? "20% auto" : "30% auto"
  box.style.gridTemplateRows = a ? "50px 50px" : "150px 188px"
  a = !a
}, 500)
.box {
  display: grid;
  grid-template-columns: 33% auto;
  grid-template-rows: 150px 188px;
}
<div id="box" class="box">
  <div id="box1"><a href="#">box1</a></div>
  <div id="box2"><a href="#">box2</a></div>
  <div id="box3"><a href="#">box3</a></div>
  <div id="box4"><a href="#">box4</a></div>
</div>

Upvotes: 3

Related Questions