代码之家  ›  专栏  ›  技术社区  ›  Arie B

带边距/填充的css网格全屏

  •  -3
  • Arie B  · 技术社区  · 7 年前

    有了css网格,我需要一个固定页眉,导航和页脚的全屏,唯一的文章是flex。

    With margin = 0px it is OK

    但如果利润率=10px,就不好了 since footer is not fixed below

    我怎样才能保持全屏的固定页眉,导航和页脚(只有文章是灵活的)也与利润=20px?

    2 回复  |  直到 6 年前
        1
  •  2
  •   Vadim Ovchinnikov    7 年前

    检查 MDN article 对于 box-sizing . 默认情况下 箱形尺寸 属于 body 设置为 content-box 这意味着:

    宽度和 高度 属性包括内容,但不包括填充、边框或边距。

    height 你的身体属性是 100vh ,但当你设置 margin 需要 100vh + 2 * 20px ,这就是 更多 100VH .

    为了防止这种情况,你必须 边缘 考虑到 height: calc(100vh - 40px); 身体上:

    body {
      display: grid;
      grid-template-areas:
        "header header header"
        "nav article article"
        "nav footer footer";
      grid-template-rows: 80px 1fr 70px;
      grid-template-columns: 20% 1fr 15%;
      grid-row-gap: 10px;
      grid-column-gap: 10px;
      height: calc(100vh - 40px);
      border-radius: 10px;
      padding: 0px;
      margin: 20px;
      font-size: 150%;
    }
    
    header,
    footer,
    article,
    nav,
    div {
      background-color: #444;
      color: #fff;
      border-radius: 10px;
      padding: 20px;
      font-size: 150%;
    }
    
    #pageHeader {
      grid-area: header;
    }
    
    #pageFooter {
      grid-area: footer;
    }
    
    #mainArticle {
      grid-area: article;
      background-color: #379;
    }
    
    #mainNav {
      grid-area: nav;
    }
    
    /* Stack the layout on small devices/viewports. */
    @media all and (max-width: 975px) {
      body {
        grid-template-areas:
          "header"
          "nav"
          "article"
          "article"
          "footer";
        grid-template-rows: 80px 1fr 70px 1fr 70px;
        grid-template-columns: 1fr;
      }
    }
    <header id="pageHeader">Header</header>
    <article id="mainArticle">Article</article>
    <nav id="mainNav">Nav</nav>
    <footer id="pageFooter">Footer</footer>
        2
  •  1
  •   Mihai T    7 年前

    所以你的问题基本上是,当你添加边距或填充时,为什么身体占据更多的空间?

    常识是,如果向元素添加一些内容(如边距或填充),则默认情况下该元素将占用更多空间以增加。

    请看一看css框模型。阅读此处-> box model 或者这里 box model

    重要提示:使用css设置元素的宽度和高度属性时,只需设置内容区域的宽度和高度。要计算元素的完整大小,还必须添加填充、边框和边距。

    拥有 height:100vh 一起 margin:20px 您需要从 100vh 具有 calc() . 所以密码是 body { height: calc(100vh - 40px)} 。你减法 40px 因为 保证金:20便士 等于 margin-top:20px;margin-right:20px;margin-bottom:20px;margin-left:20px 所以你有 top-bottom : 20+20 = 40px 保证金。

    你可以用的垫子 box-sizing:border-box ->此处更多 box-sizing

    边框宽度和高度属性(以及最小/最大属性)包括内容、填充和边框

    body {
    margin:20px;
    height:calc(100vh - 40px);
    padding:20px;
    box-sizing:border-box;
    background:red;
    }
      
    推荐文章