display: grid导致<nav>元素max-width属性失效,宽度受限的问题咨询
Let's break down exactly what's happening here:
The Root Cause
When you set body { display: grid; place-items: center; }, you're turning the <body> into a grid container, and <nav> becomes its only grid item.
The place-items: center property is a shorthand for align-items: center (vertical centering) and justify-items: center (horizontal centering). Here's the key detail: justify-items: center tells grid items to shrink-to-fit their content width instead of stretching to fill the available space in the grid container.
Your nav { max-width: 90%; } rule doesn't work as expected because the grid container (body) is only giving the <nav> a width equal to its content's maximum width (your longest nav link, which ends up being ~325.8px). The max-width:90% is relative to this constrained width, not the full viewport width.
Why Removing display: grid Fixes It
When <body> isn't a grid container, <nav> acts like a normal block-level element. Block elements default to width: 100% of their parent's available space (the viewport, in this case), so max-width:90% correctly caps it at 90% of the viewport width.
Fixes to Try
You have a few straightforward solutions to keep the grid layout for centering while fixing the <nav> width issue:
Force the nav to stretch horizontally
Addjustify-self: stretchto the<nav>styles. This overrides thejustify-items: centerinherited from the body, making the nav fill the grid container's available space, whilemax-width:90%still applies:nav { max-width: 90%; justify-self: stretch; }Adjust the body's grid alignment
If you want all grid items (nav, main, footer) to stretch horizontally but stay vertically centered, replaceplace-items: centerwith explicit alignment properties:body { font-size: 1.6rem; height: 100%; display: grid; align-items: center; /* Keep vertical centering */ justify-items: stretch; /* Make items fill horizontal space */ }Define a grid column that fills the viewport
Addgrid-template-columns: 1frto the body. This creates a single grid column that takes up all available viewport width, so the nav will inherit this width and respect yourmax-width:90%rule:body { font-size: 1.6rem; height: 100%; display: grid; place-items: center; grid-template-columns: 1fr; }
内容的提问来源于stack exchange,提问作者Yahx

