Search code examples
htmlcssalignmentcss-grid

Expanding to fill remaining space in a CSS Grid layout


I want to use CSS grid and the following is a mock-up of the aim:enter image description here

I'm building an interface that should expand rightward to fill the browser screen; my current code causes column 2 of the outer grid to be as wide as the browser in addition to column 1; or maybe one of it's children is causing this and it's just expanding to accommodate. Either way, it's spilling off the page horizontally

So the code:

#main {
  width: 100%;
  display: grid;
  grid-template-columns: 250px 100%;
  grid-template-rows: 100px 100%;
}

#col-2-outer {
  display: grid;
  grid-template-columns: 250px auto;
  grid-template-rows: 100%;
}

#row-1-inner {
  grid-column: span 2;
}

#col-2-inner table {
  width: 100%;
}
<div id="main">
  <div id="col-1-outer"></div>
  <div id="col-2-outer">
    <div id="row-1-inner"></div>
    <div id="row-2-inner">
      <div id="col-1-inner"></div>
      <div id="col-2-inner">
        <table></table>
      </div>
    </div>
  </div>
</div>

FYI, for the time being I've forgone template areas until I get a handle on the basics (unless this somehow solves my problem but I gather this is strictly a code organization feature?).


Solution

  • The 100% for the 2nd column in your grid-template-columns is based on the width of the container - rather than occupying the space outstanding within the container, it will push out to the right because the 2nd column is trying to match the width of the container.

    Try changing this to auto and this should rectify the issue, as it will only take up the space up to the end of the container and no further.

    Source: https://developer.mozilla.org/en-US/docs/Web/CSS/grid-template-columns