Home > other >  How to use CSS Grid to make layout where one column has a maximum size
How to use CSS Grid to make layout where one column has a maximum size

Time:11-19

I'm trying to make a layout with a "page". I would have 3 columns, 1st and 3th would use only 10% of the space, and the middle 80%. Until there no problem. But I would like that as soon as the middle part reach 64rem, it's only the first and last column that grow.

Currently I've tried this:

.container {
  display: grid;
  grid-template-columns: 10% minmax(80%, 64rem) 10%;
  grid-template-rows: min-content auto;
  min-height: 100vh;
  background-color: red;
}

.header {
  grid-column-start: 2;
  grid-column-end: 3;
  grid-row-start: 1;
  grid-row-end: 2;
  background-color: blue;
}

.content {
  grid-column-start: 2;
  grid-column-end: 3;
  grid-row-start: 2;
  grid-row-end: 3;
  background-color: yellow;
}
<div >
  <div >
    header
  </div>
  <div >
    content
  </div>
</div>

But it doesn't stops at 64rem. Any idea how to adress this issue?

CodePudding user response:

You need to think otherwise and set width and max-width on the container itself. your template becomes then : 1fr auto 1fr , wher both sides will grow as much as the middle column will allow them to.

Example below

.container {
  display: grid;
  grid-template-columns: 1fr auto 1fr;
  grid-template-rows: min-content auto;
  min-height: 100vh;
  background-color: red;
}

.header {
  grid-column-start: 2;
  grid-column-end: 3;
  grid-row-start: 1;
  grid-row-end: 2;
  background-color: blue;
}

.content {
  grid-column-start: 2;
  grid-column-end: 3;
  grid-row-start: 2;
  grid-row-end: 3;
  background-color: yellow;
  width:80vw;/* where the parent container fills the whole screen's width */
  max-width:64rem;
}
<div >
  <div >
    header
  </div>
  <div >
    content
  </div>
</div>

CodePudding user response:

Replace the 10% with 1fr and consider min() instead of minmax(). I used 32rem instead of 64rem to easily demonstrate the trick

.container {
  display: grid;
  grid-template-columns: 1fr min(80%, 32rem) 1fr;
  grid-template-rows: min-content auto;
  min-height: 100vh;
  background-color: red;
}

.header {
  grid-column: 2;
  background-color: blue;
}

.content {
  grid-column: 2;
  background-color: yellow;
}
<div >
  <div >
    header
  </div>
  <div >
    content
  </div>
</div>

You can also use padding and simplify the code like below:

.container {
  display: grid;
  padding-inline: max(10%,(100% - 32rem)/2);
  grid-template-rows: min-content 1fr;
  min-height: 100vh;
  background-color: red;
}

.header {
  background-color: blue;
}

.content {
  background-color: yellow;
}
<div >
  <div >
    header
  </div>
  <div >
    content
  </div>
</div>

  • Related