这个问题在这里已有答案:
我正在使用一些弹性框属性将一个简单的div放到屏幕的中心:
//CSS
html {
width: 100%;
height: 100%;
}
body {
width: 100%;
height: 100%;
margin: 0px;
display: flex;
align-items: center;
justify-content: center;
}
div {
height: 500px;
width: 500px;
background-color: red;
border: 5px solid black;
}
//HTML
<div></div>
它工作得很完美但是当我将屏幕高度减小到小于我的div(小于500px)时,我最终会出现一个奇怪的截断:我可以向下滚动并看到底部边框但是出于某种原因我向上滚动我无法到达顶部边界,它是隐藏的。
我错过了什么吗?谁知道如何解决这个问题?我创建了一个codepen来演示这个问题:https://codepen.io/stepinsight/full/MqmEME
谢谢你的帮助!
相反align-items:center;
你可以在flex儿童使用margin:auto
来居中它:
html {
width: 100%;
height: 100%;
}
body {
width: 100%;
height: 100%;
margin: 0px;
display: flex;
justify-content: center;
}
div {
height: 500px;
width: 500px;
background-color: red;
border: 5px solid black;
margin:auto;
}
<div></div>
fork of your pen注意:justify-content
也会被删除,当margin:auto;
为flex
孩子的两个轴工作时。 flex-shrink:0;
也被添加,因此容器不会水平缩小(并且还隐藏左边框),而screeen的宽度也变小。