首页 > 解决方案 > 为什么我的 CSS Grid 容器偏离了 1 个像素?

问题描述

当我在 Chrome DevTools 中检查我的布局网格容器时,我的网格似乎被向右推了 1 个像素。我能够看到网格的左侧边框,但右侧边框不在屏幕上。

问题截图:Off-by-1 CSS 网格容器

这个问题的原因可能是什么?

我有以下全局CSS:

html, body {
  height: 100%;
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

以及我的网格容器的以下 CSS:

.container {
  background-color: #F5F6F9;
  position: relative;
  min-height: 100vh;
  display: grid;
  grid-template-columns: 100px minmax(1080px, 1fr) 100px;
  grid-template-rows: 75px minmax(150px, 1fr) 75px;
  grid-template-areas: 
  "header header header"
  ". main ."
  "footer footer footer";
}

我想也许添加box-sizing: border-box到全局 css 可以解决这个问题,但没有任何改变。

标签: cssbrowserfrontendcss-griddisplay

解决方案


I dont know if this is the solution you are looking for, but HTML body have a safe space of 8px as its margin. So when you set the margin: 0px; , you also remove the safe space along with it. However, you can always set the margin-right to 1px so you can see the border.

Forced method, change your body margin:

html, body {
  height: 100%;
  padding: 0;
  margin: 0px 1px 0px 0px;
  box-sizing: border-box;
}

推荐阅读