css 网格全屏 margin/padding

css grid full screen with margin/padding

使用 CSS 网格,我需要一个带有固定页眉、导航和页脚的全屏,只有文章是 flex。

With margin = 0px it is OK

但是 margin = 10px 不行 since footer is not fixed below

如何在固定页眉、导航和页脚(只有文章是 flex)以及边距 = 20px 的情况下保持全屏显示?

检查 MDN article box-sizing。 默认情况下 bodybox-sizing 设置为 content-box – 这意味着:

The width and height properties include the content, but does not include the padding, border, or margin.

height 属性 of body in your case is 100vh, but when you set margin – it takes 100vh + 2 * 20px, which is 100vh.

为了防止这种情况,您必须考虑 margin – 在主体上设置 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>

所以你的问题基本上是为什么当你添加边距或填充时正文占据更多space?

这是常识,如果你给一个元素添加一些东西,比如 margin 或 padding,那个元素占用更多 space 默认增加。

请看一下CSS盒子模型。阅读此处 -> box model or here box model

Important: When you set the width and height properties of an element with CSS, you just set the width and height of the content area. To calculate the full size of an element, you must also add padding, borders and margins.

要让 height:100vhmargin:20px 一起使用,您需要用 calc()100vh 中减去该边距。所以代码是 body { height: calc(100vh - 40px)} 。你减去 40px 因为 margin:20px 等于 margin-top:20px;margin-right:20px;margin-bottom:20px;margin-left:20px 所以你有 top-bottom : 20+20 = 40px 余量。

对于填充,您可以使用 box-sizing:border-box -> 更多信息 box-sizing

border-box The width and height properties (and min/max properties) includes content, padding and border

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