search

Home  >  Q&A  >  body text

Why does a grid child with a fixed width and a max width of 90% overflow the grid track?

question:

My question is very simple, I want to know why the .header element overflows its grid track when it reaches the viewport width of 1500 pixels.

Code:

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

body {
  background: #6e28d9;
  color: white;
}

.container {
  display: grid;
  grid-template-areas: 'header';
  grid-template-columns: 1fr;
  background-color: rgba(255, 255, 255, 0.2);
}

.header {
  display: flex;
  justify-content: space-between;
  grid-area: header;
  width: 1500px;
  max-width: 90%;
  margin: 0 auto;
}
<body>
    <div class="container">
      <div class="header">
        <div class="header-start">header start</div>
        <div class="header-end">header end</div>
      </div>
    </div>
  </body>

The effect I want:

My idea is to make the width of the .header element 1500 pixels. When space is insufficient, .header should occupy 90% of its grid track.

What I tried:

I successfully achieved this effect by setting width: min(1500px, 90%) and deleting max-width in the .header element, But I don't know exactly what happened. I'm guessing the grid track calculates its width based on the width of its content. At the moment I'm not sure what the exact meaning of 1fr is.

my thoughts:

Everyone says Grid is great, but I always run into trouble when I leave the warmth of Flexbox.

P粉471207302P粉471207302236 days ago1546

reply all(1)I'll reply

  • P粉238433862

    P粉2384338622024-04-06 12:19:12

    Using 90vw instead of 90% seems to work for this

    *{
      box-sizing: border-box;
      padding: 0;
      margin: 0;
    }
    
    body {
      background: #6e28d9;
      color: white;
    }
    
    .container{
      display: grid;
      grid-template-areas: 'header';
      grid-template-columns: 1fr;
      background-color: rgba(255, 255, 255, 0.2);
    }
    
    .header{
      display: flex;
      justify-content: space-between;
      grid-area: header;
      width: 1500px;
      max-width: 90vw;
      margin: 0 auto;
    
      border: 1px solid red; /*Added just to visualize the exact width*/
    }
    <div class="container">
      <div class="header">
        <div class="header-start">header start</div>
        <div class="header-end">header end</div>
      </div>
    </div>

    reply
    0
  • Cancelreply