You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

display: grid导致<nav>元素max-width属性失效,宽度受限的问题咨询

Why does display: grid on <body> limit the width of <nav>?

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:

  1. Force the nav to stretch horizontally
    Add justify-self: stretch to the <nav> styles. This overrides the justify-items: center inherited from the body, making the nav fill the grid container's available space, while max-width:90% still applies:

    nav {
      max-width: 90%;
      justify-self: stretch;
    }
    
  2. Adjust the body's grid alignment
    If you want all grid items (nav, main, footer) to stretch horizontally but stay vertically centered, replace place-items: center with 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 */
    }
    
  3. Define a grid column that fills the viewport
    Add grid-template-columns: 1fr to the body. This creates a single grid column that takes up all available viewport width, so the nav will inherit this width and respect your max-width:90% rule:

    body {
      font-size: 1.6rem;
      height: 100%;
      display: grid;
      place-items: center;
      grid-template-columns: 1fr;
    }
    

内容的提问来源于stack exchange,提问作者Yahx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 18:14:09