Home > Net >  How to create page layout with grid, where the outside columns work as an automatic "Margin&quo
How to create page layout with grid, where the outside columns work as an automatic "Margin&quo

Time:11-10

I am looking to use css grid for layout on a page. And need a way to add a max width to 2 columns.

I need to use 4 columns where the inside 2 have a max width and the two outer ones to automatically scale depending on the browser window. I then need one of the child elements to span the 3rd and 4th columns.

Please see below for an example: Example of what I am trying to achieve

I have tried the following:

grid-template-columns: auto 800px 800px auto;

But the "Auto" columns are not the same size, the whole grid is pushed to the left.

It also needs to be responsive, so that when you get to below 1600px the outside columns don't take up any space and the middle two take up 50% each.

I have also tried to use:

grid-template-columns: 1fr 800px 800px 1fr;

But this solution doesn't work when the browser window is resized as anything below 1600px goes off screen.

Working example on Codepen: https://codepen.io/Rubenkretek/pen/xxLzRwq

CodePudding user response:

use 1fr instead auto, so they have the same size : grid-template-columns: 1fr 800px 800px 1fr;

Possible example

main {
  display: grid;
  grid-template-columns: 1fr 800px 800px 1fr;
  min-height: 50vh;
  width: max-content;
}

section {
  display: grid;
  grid-template-columns: minmax(calc(200px   2em ), 1fr) 800px 800px minmax(200px, 1fr);
  min-height: 50vh;
  width: max-content;
}

main:before,
section:before {
  /* fills first cell*/
  content: '';
  grid-column: 1;
}

div,
aside {
  padding: 1em;
  border: solid;
}

section div {
  grid-column: 2;
}

section div div {
  grid-column: 3 /span 2;
}

aside {
  width: 200px;
}
<main>
  <div>L</div>
  <div>R</div>
  <aside> Aside </aside>
</main>
<hr>
<section>
  <div>L</div>
  <div>R</div>
</section>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

The solution is to use fr for the outside columns with a defined with of the inside columns:

grid-template-columns: 1fr 800px 800px 1fr;

And then to add a media query which changes the inside boxes to a percentage on widths below 1600px:

@media (max-width: 1600px) {  
    grid-template-columns: 1fr 1fr; 
}

The position of child elements needs to be adjust accordingly

  • Related