Search code examples
csscss-grid

CSS: Align grid header with grid elements


I am trying to create a grid layout in CSS. I want to put a header above the grid. I want the left edge of the header to align with the left edge of the first item in the grid. I have created a snippet of my grid. See how when you drag the grid's container to resize it the width between the grid's elements and the edge of the container is not the same.

How do I make my header align with the leftmost edge of the grid elements?

Edit: I want the grid items to be centered when there is extra horizontal space. Setting justify-content: left; is not the solution.

.page {
  min-width: 300px;
  background: lightgray;
  padding: 12px;
  resize: horizontal;
  overflow: auto;
}

.grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, 140px);
    grid-column-gap: 12px;
    grid-row-gap: 12px;
    width: 100%;
    justify-content: center;
}

.grid-element {
  color: #fff;
  overflow: hidden;
  height: 82px;
  background: white;
}
<div class="page">
  <p>Grid Header</p>
  <div class="grid">
    <div class="grid-element"></div>
    <div class="grid-element"></div>
    <div class="grid-element"></div>
    <div class="grid-element"></div>
    <div class="grid-element"></div>
  <div>
</div>


Solution

  • I would simply add the title as an element inside the grid that span all the first row

    .page {
      min-width: 300px;
      background: lightgray;
      padding: 12px;
      resize: horizontal;
      overflow: auto;
    }
    
    .grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, 140px);
        grid-column-gap: 12px;
        grid-row-gap: 12px;
        width: 100%;
        justify-content: center;
    }
    
    .grid-element {
      color: #fff;
      overflow: hidden;
      height: 82px;
      background: white;
    }
    .grid  p {
      grid-row:1;
      grid-column:1/-1;
    }
    <div class="page">
      <div class="grid">
        <p>Grid Header</p>
        <div class="grid-element"></div>
        <div class="grid-element"></div>
        <div class="grid-element"></div>
        <div class="grid-element"></div>
        <div class="grid-element"></div>
      <div>
    </div>