Home > OS >  CSS Grid with vertical and horizontal overflow
CSS Grid with vertical and horizontal overflow

Time:06-11

I'm trying to use display: grid to make a layout with a variable amount of columns, with horizontal and vertical overflow and the first column being a specific width.

Each of the columns, besides the first, should be the same width. For example,

grid-template-columns: 49px repeat(auto-fill, 300px);

makes the first column the correct width, and columns after 300px - until reaching the overflowing columns, which ignore the 300px.

The vertical scroll is achieved with overflow-y and a specified height.

overflow-y: scroll;
height: 70vh;

And the horizontal css so far is:

grid-template-columns: 49px repeat(auto-fit, 300px);
grid-auto-flow: column;
overflow-x: scroll;
width: 100%;

Stack snippet:

.grid-container {
  display: grid;
  grid-template-columns: 49px repeat(auto-fit, 300px);
  grid-auto-flow: column;
  overflow-x: scroll;
  width: 100%;
  overflow-y: scroll;
  height: 70vh;
}
<div >
  <div >1</div>
  <div >2</div>
  <div >3</div>
  <div >4</div>
  <div >5</div>
  <div >6</div>
  <div >7</div>
  <div >8</div>
</div>

Paint attempt to visualise the goal: Grid Paint Example

CodePudding user response:

You could solve this by omitting grid-template-columns and defining the width separately:

.grid-container {
  display: grid;
  grid-auto-flow: column;
  overflow-x: scroll;
  width: 100%;
  overflow-y: scroll;
  height: 70vh;
}

.first-item {
  width: 49px;
}

.item {
  width: 300px;
}
<div >
  <div >1</div>
  <div >2</div>
  <div >3</div>
  <div >4</div>
  <div >5</div>
  <div >6</div>
  <div >7</div>
  <div >8</div>
</div>

CodePudding user response:

Use grid-auto-columns and you don't need to specify any CSS on the child items

.grid-container {
  display: grid;
  grid-template-columns: 49px; /* 1st column */
  grid-auto-columns: 300px; /* all the others */
  grid-auto-flow: column;
  overflow-x: scroll;
  height: 70vh;
}
<div >
  <div >1</div>
  <div >2</div>
  <div >3</div>
  <div >4</div>
  <div >5</div>
  <div >6</div>
  <div >7</div>
  <div >8</div>
</div>

  •  Tags:  
  • css
  • Related