skip to Main Content

I have a CSS grid which is wider than the viewport. I want to be able to scroll right to reveal the rest of the grid but for some reason the background color of the grid is only the size of the viewport so when I start scrolling right there is no background.

.table {
  background-color: blue;
  display: grid;
  gap: 4px;
  grid-template-columns: repeat(6, 50%);
}

.element {
  background-color: lightblue;
  word-break: break-all;
  white-space: nowrap;
}
<div class="table">
  <div class="element">this is an element of the grid</div>
  <div class="element">this is an element of the grid</div>
  <div class="element">this is an element of the grid</div>
  <div class="element">this is an element of the grid</div>
  <div class="element">this is an element of the grid</div>
  <div class="element">this is an element of the grid</div>
</div>

2

Answers


  1. This is happening because currently the div "table" is overflowing out of the viewport, since the background color is limited only to this div and not the viewport you are unable to see it. You need to give this div a fix width/max-width and set overflow-x: auto; to achieve your desired result, this limits the div to overflow within the viewport.

    .table {
      background-color: blue;
      display: grid;
      gap: 4px;
      grid-template-columns: repeat(6, 50%);
      /* adding a fixed width limits this div to overflow within the viewport */
      max-width: 100vw;
      overflow-x: auto;
    }
    
    .element {
      background-color: lightblue;
      word-break: break-all;
      white-space: nowrap;
    }
    <div class="table">
      <div class="element">this is an element of the grid</div>
      <div class="element">this is an element of the grid</div>
      <div class="element">this is an element of the grid</div>
      <div class="element">this is an element of the grid</div>
      <div class="element">this is an element of the grid</div>
      <div class="element">this is an element of the grid</div>
    </div>
    Login or Signup to reply.
  2. This probably happens because the repeat(6,50%) is messing things up. If you change it to 50vw (50% of the viewport) or 1fr and set the grid to inline-grid this works as expected:

    .table {
      background-color: blue;
      display: inline-grid;
      gap: 4px;
      grid-template-columns: repeat(6, 50vw);
    }
    
    .element {
      background-color: lightblue;
      white-space: nowrap;
    }
    <div class="table">
      <div class="element">this is an element of the grid</div>
      <div class="element">this is an element of the grid</div>
      <div class="element">this is an element of the grid</div>
      <div class="element">this is an element of the grid</div>
      <div class="element">this is an element of the grid</div>
      <div class="element">this is an element of the grid</div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search