Search code examples
htmlcsscss-grid

Grid-column-end with items that have a fixed width not aligning


I have an item that needs to have a fixed width, but when I try and right-align it to a certain column, it overflows. Removing the width fixes the problem, but that's unfortunately not a solution I can use.

Using grid-column to set the width works, but I want to have greater control over the size of the item, if possible.

I also tried making the container span grids 1/4 and then aligned content inside of it, but I'm getting something wrong because that doesn't quite work.

* {
  margin: 0;
  box-sizing: border-box;
}

.container {
  display: grid;
  grid-template-columns: repeat(16, minmax(0, 1fr));
  grid-gap: 1rem;
  align-content: start;
  height: 100vh;
  width: 100%;
  padding: 1rem;
  background-color: firebrick;
}
.section {
  display: flex;
  justify-content: center;
  align-items: center;
 
  height: 8rem;

  background-color: white;
}

.section-1 {
    grid-column: 1/4;
}
.section-2 {
  grid-column: 1/4;
}
.section-3 {
  grid-column: 4/6;
  grid-row-start: 1;
}

.controls {
  width: 9rem;
  height: 3rem;
  grid-column-end: 4;
  background-color: white;
}
<div class="container">
  <div class="section section-1">Section 1</div>
  <div class="controls">
    <div class="control-btn"></div>
    <div class="control-btn"></div>
    <div class="control-btn"></div>
  </div>
  <div class="section section-2">Section 2</div>
  <div class="section section-3">Section 3</div>
</div>

Grid alignment problem

CodePen demo


Solution

  • add justify-self: end; to that item but you can get overflow on the left side

    * {
      margin: 0;
      box-sizing: border-box;
    }
    
    .container {
      display: grid;
      grid-template-columns: repeat(16, minmax(0, 1fr));
      grid-gap: 1rem;
      align-content: start;
      height: 100vh;
      width: 100%;
      padding: 1rem;
      background-color: firebrick;
    }
    .section {
      display: flex;
      justify-content: center;
      align-items: center;
     
      height: 8rem;
    
      background-color: white;
    }
    
    .section-1 {
        grid-column: 1/4;
    }
    .section-2 {
      grid-column: 1/4;
    }
    .section-3 {
      grid-column: 4/6;
      grid-row-start: 1;
    }
    
    .controls {
      width: 9rem;
      height: 3rem;
      grid-column-end: 4;
      background-color: white;
      justify-self:end;
    }
    <div class="container">
      <div class="section section-1">Section 1</div>
      <div class="controls">
        <div class="control-btn"></div>
        <div class="control-btn"></div>
        <div class="control-btn"></div>
      </div>
      <div class="section section-2">Section 2</div>
      <div class="section section-3">Section 3</div>
    </div>