html - flex 容器内的居中元素正在增长并溢出到顶部

标签 html css flexbox

<分区>

我一定是忘记了我的垂直和水平居中 flexbox 的一些基本知识。

容器位于垂直滚动的父容器内,当容器变得太高时,它会超出父容器的顶部,从而剪裁内容。底部保持不变。

尝试调整 View 的高度或添加更多行以查看实际效果。

body,
html {
  height: 100%;
  width: 100%;
  margin: 0;
}

* {
  box-sizing: border-box;
}

#wrapper {
  background: grey;
  height: 100%;
  width: 100%;
  max-height: 100%;
  display: flex;
  overflow-y: auto;
  align-items: center;
  justify-content: center;
}

#box {
  margin: 30px 0;
  background: white;
  border: 1px solid #dfdfdf;
}
<div id="wrapper">
  <div id="box">
    First line
    <br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br> Last linje
  </div>
</div>

如何防止它被剪裁?此外,我正在尝试在容器上方和下方留出 30 像素的边距。

谢谢!

最佳答案

您什么都没忘记,只是您需要了解正在发生的事情。首先,您将包装器设为屏幕的 100% 高度,然后将盒子设为垂直和水平居中。当盒子有很大的高度时,你会得到这样的东西:

enter image description here

现在,当您添加 overflow-y: auto您将创建一个滚动条,该滚动条将从包装器的顶部 开始,直到底部溢出内容。所以它会是这样的:

enter image description here

这就是为什么您可以滚动到底部以查看底部而看不到顶部的原因。

为避免这种情况,请使用 margin:auto使您的元素居中,在这种情况下,我们将有两种情况:

  1. 何时box-height < wrapper-height由于 margin:auto,我们将在每一侧均匀分布空间因此您的元素将像预期的那样居中
  2. 何时box-height > wrapper-height我们将有正常的行为,您的元素将溢出并且他的顶部边缘将粘在包装器的顶部边缘

enter image description here

您可能还会注意到同样的情况也会发生在水平方向上,这就是为什么我会在两个方向上使用边距居中。

body,
html {
  height: 100%;
  width: 100%;
  margin: 0;
}

* {
  box-sizing: border-box;
}

#wrapper {
  background: grey;
  height: 100%;
  width: 100%;
  max-height: 100%;
  padding:30px 0;
  display: flex;
  overflow-y: auto;
}

#box {
  margin: auto;
  background: white;
  border: 1px solid #dfdfdf;
}
<div id="wrapper">
  <div id="box">
    First line
    <br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br> Last linje
  </div>
</div>

关于html - flex 容器内的居中元素正在增长并溢出到顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49278725/

相关文章:

javascript - 我们可以在 css 中使用百分比高度吗?

javascript - 使用 Javascript 注册 `keydown` 事件后 Textarea 滞后

html - 如果鼠标按下时移动光标,则标签不会切换

html - 如何使div先垂直堆叠然后水平堆叠?

css - 如何在文档中居中一个灵活的框?

html - 具有柔性显示的并排画廊

html - aria - 多行用途

css - 如何将我的幻灯片放在段落旁边

html - 如何向 CSS Sprite 添加文本

javascript - 检查输入是否已填充