flex容器内居中的元素正在增长并且溢出到顶部之外

我必须忘记垂直和水平居中的flexbox的一些基本知识。


容器位于具有垂直滚动的父对象内,并且当容器太高时,它会超出父对象顶部,剪切内容。底部保持不变。


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


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>

如何防止其被修剪?另外,我尝试在容器上方和下方设置30px的边距。



慕运维8079593
浏览 755回答 3
3回答

慕村225694

我认为您想要的是使flex项目(#box)具有高度并设置其溢出范围,而不是flex容器。另外,要在上方和下方添加30px,我会从框中删除边距,而是向容器中添加填充。因此,更新后的样式将如下所示:#wrapper {&nbsp; background: grey;&nbsp; height: 100%;&nbsp; width: 100%;&nbsp; max-height: 100%;&nbsp; display: flex;&nbsp; &nbsp; &nbsp;&nbsp;&nbsp; align-items: center;&nbsp; justify-content: center;&nbsp; padding: 30px 0; /*added*/}#box {&nbsp; background: white;&nbsp; border: 1px solid #dfdfdf;&nbsp; overflow-y: auto; /*added*/&nbsp; height: 100%; /*added*/}body,html {&nbsp; height: 100%;&nbsp; width: 100%;&nbsp; margin: 0;}* {&nbsp; box-sizing: border-box;}#wrapper {&nbsp; background: grey;&nbsp; height: 100%;&nbsp; width: 100%;&nbsp; max-height: 100%;&nbsp; display: flex;&nbsp; &nbsp; &nbsp;&nbsp;&nbsp; align-items: center;&nbsp; justify-content: center;&nbsp; padding: 30px 0;}#box {&nbsp; &nbsp;&nbsp;&nbsp; background: white;&nbsp; border: 1px solid #dfdfdf;&nbsp; overflow-y: auto;&nbsp; height: 100%;}<div id="wrapper">&nbsp; <div id="box">&nbsp; &nbsp; First line&nbsp; &nbsp; <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&nbsp; </div></div>

开心每一天1111

我认为您在box类中设置了顶部边距,从而扩展了容器的高度。您可以将其设置为padding而不是margin。希望这可以帮助。谢谢。
打开App,查看更多内容
随时随地看视频慕课网APP