CSS Grid resizable cell

Asked by At

In the following layout, I want to make the green color section to be re sizable. When it's resized, cell 8 should take the whatever the space left without affecting any other cells in other rows.

.App {
  display: grid;
  
  grid-template-columns: 200px 1fr 200px;
  grid-template-rows: 50px 1fr 200px 30px;

  width: 100%;
  height: 100%;
}

.App > div {
  border: 2px solid black;
}

.nav {
  background: green;
}
<div class="App">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
  <div>6</div>
  <div class="nav">7</div>
  <div>8</div>
  <div>9</div>
  <div>10</div>
  <div>11</div>
  <div>12</div>
</div>

Size change will be done by the user. But to demonstrate, consider changing width of the .nav element to 100px. After size of .nav is changed, 8 cell should take the remaining space and grow.

.nav {
    background: green;
    width: 100px;
}

Is this kind of a behavior is possible using CSS Grid?

1 Answers

1
kukkuz On Best Solutions

You can't change nav width and expect that it only affect the element next to it - it affect the whole first column. You can try resizing the nav in the demo below (using grid-template-columns: auto 1fr 200px) along with sufficient min-width and max-width:

.App {
  display: grid;
  grid-template-columns: auto 1fr 200px; /* changed */
  grid-template-rows: 50px 1fr 200px 30px;
}

.App > div {
  border: 2px solid black;
}

.nav {
  background: green;
  width: 100px; /* default width */
  max-width: calc(100vw - 260px); /* do go beyond the third column */
  min-width: 25px; /* min width of nav */
  resize: horizontal; /* resize the div */
  overflow: hidden; /* resize works if overflow not visible */
}
<div class="App"><div>1</div><div>2</div><div>3</div><div>4</div><div>5</div><div>6</div><div class="nav">7</div><div>8</div><div>9</div><div>10</div><div>11</div><div>12</div></div>


That's as far as you can have with the current markup. If you can change your html by wrapping the 8 and 7 into a 2-column grid item and make if a flexbox, you can have the desired effect - see demo below:

* {
box-sizing: border-box;
}

.App {
  display: grid;
  grid-template-columns: 1fr 1fr 200px;
  grid-template-rows: 50px 1fr 200px 30px;
}

.App > div {
  border: 2px solid black;
}

.nav {
  grid-column: span 2;
  display: flex;
}
.nav > div:first-child {
  background: green;
  resize: horizontal;
  overflow: hidden;
  width: 50%;
}
.nav > div:last-child {
  flex: 1;
  width: 50%;
}
<div class="App">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
  <div>6</div>
  <div class="nav">
    <div>7</div>
    <div>8</div>
  </div>
  <div>9</div>
  <div>10</div>
  <div>11</div>
  <div>12</div>
</div>

You can read more about flexboxes with a resizable slider in these posts: