Question:
My question is very simple, I need to know why the .header
element is overflowing its grid track when reaching the 1500px viewport width.
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>
What I wanted:
The idea is having the .header
element have a width of 1500px. When there is not enough room, .header
should take 90% of its grid track.
What I tried:
I managed to get it done by setting width: min(1500px, 90%)
and removing max-width
in the .header
element, but don’t really know what is happening. My guess is that grid track is calculating its width based on the width if the content. At this point I’m not really sure what 1fr
really means.
Thoughts:
Everybody says that Grid is great but trouble always finds me when I leave the warmth of my Flexbox.
2
Answers
Using
90vw
instead of90%
seems to work for thisI think, You are misunderstanding about Max-width, width and % in CSS.
In CSS, the element’s width:10% means 10% of parent div’s width. And pixel unit is static value in CSS.
Also the parent’s min width is same with child div’s width.
In your project, You set header’s width as 1500px, so the parent element’s minimal width is 1500px. As the result, the 90% of header is at least 1350px.
Please check the width of header’s width using inspect in chrome, then you will notice that the minimal width of header is 1350px even you resize the width of the chrome viewport under 1500px.
That’s because you set the width of header as 1500px, which means the min-width of parent div is 1500px.
To fix your code, please exchange two values of width and max-width. Then everything works good.
PS: you will see that when you resize the viewport under 1500px, then the letters are getting smaller than it’s normal size. that’s because the size of pixel is getting smaller relatively.