Why does a grid child with a fixed width and a max width of 90% overflow the grid track?
P粉471207302
P粉471207302 2024-04-05 14:33:39
0
1
1520

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粉471207302
P粉471207302

reply all(1)
P粉238433862

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>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template