我的问题非常简单,我想知道为什么.header元素在达到1500像素的视口宽度时会溢出其网格轨道。
代码:
* {
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>
我的想法是让.header元素的宽度为1500像素。当空间不足时,.header应该占据其网格轨道的90%。
我通过设置width: min(1500px, 90%)并在.header元素中删除max-width,成功实现了这个效果,但我不知道具体发生了什么。我猜测网格轨道是根据内容的宽度来计算其宽度的。目前我不太确定1fr的确切含义是什么。
每个人都说Grid很棒,但当我离开Flexbox的温暖时,总是遇到麻烦。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
使用
90vw而不是90%似乎对此起作用*{ 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>