带填充的CSS网格溢出容器

Sam*_*Sam 8 html css overflow css3 css-grid

我试图创建一个页脚,其宽度为(正文的)100%。在页脚的左侧,我想要一个徽标。在页脚的右侧,我想要一些文本。所以我决定尝试使用CSS网格。

这几乎正​​是我要的:

.footer {
  background-color: #2D1975;
  width: 100%;
  height: 350px;
  display: grid;
  grid-template-columns: 30% 70%;
}

.footerGridLogo {
  background-color: red;
}

.footerGridQuestions {
  background-color: green;
}
Run Code Online (Sandbox Code Playgroud)
<div class="footer">
  <div class="footerGridLogo"></div>
  <div class="footerGridQuestions"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

但是,我想在网格的左侧添加一些填充,例如10%,这样徽标就不会离左侧边缘那么近了。因此,我尝试了10-25-65的拆分,而不是30-70的拆分。但是,网格最终溢出。这是为什么?

问题的演示:

.footer {
  background-color: #2D1975;
  width: 100%;
  height: 350px;
  display: grid;
  padding-left: 10%;
  grid-template-columns: 25% 65%;
}

.footerGridLogo {
  background-color: red;
}

.footerGridQuestions {
  background-color: green;
}
Run Code Online (Sandbox Code Playgroud)
<div class="footer">
  <div class="footerGridLogo">
  </div>
  <div class="footerGridQuestions">
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

我意识到仅添加另一个10%的网格项而不是填充即可解决我的问题,但我很好奇为什么填充不能以相同的方式工作。

Mic*_*l_B 9

首先,不要使用百分比单位,而要使用fr单位。这些单位表示剩余的空间,并在呈现固定长度(例如填充)后将其考虑在内。

所以代替这个:

grid-template-columns: 30% 70%
Run Code Online (Sandbox Code Playgroud)

尝试这个:

grid-template-columns: 3fr 7fr
Run Code Online (Sandbox Code Playgroud)

更多细节:


其次,取下width: 100%容器上的。

.footer {
  background-color: #2D1975;
  width: 100%; <---------- remove
  height: 350px;
  display: grid;
  padding-left: 10%;
  grid-template-columns: 25% 65%;
}
Run Code Online (Sandbox Code Playgroud)

当您将设置为时.footerdisplay: grid它成为(或保持为)块级元素。这样的元素会自动占据父级的整个宽度。

但是,如果将其添加width: 100%到块级元素,则会在计算中添加任何填充,边距和边框,从而导致溢出。因此,只需将其删除。


第三,如果将padding-left徽标添加到徽标本身,而不是添加到网格容器或网格项目,则可以避免整个问题。


sol*_*sol 5

这是大小调整

默认值为content-box,这意味着paddingborder值已添加到中width

您可以将其更改为border-box,其中包括paddingborder宽度。

这是一个常见的方法,从这篇文章

html {
  box-sizing: border-box;
}

*,
*:before,
*:after {
  box-sizing: inherit;
}

.footer {
  background-color: #2D1975;
  width: 100%;
  height: 350px;
  display: grid;
  padding-left: 10%;
  grid-template-columns: 25% 65%;
}

.footerGridLogo {
  background-color: red;
}

.footerGridQuestions {
  background-color: green;
}
Run Code Online (Sandbox Code Playgroud)
<div class="footer">
  <div class="footerGridLogo">
  </div>
  <div class="footerGridQuestions">
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)