如何在不溢出#container的情况下正确居中#content? margin:auto有点工作,但对我来说看起来像是黑客,我不想在CSS FlexBox中使用任何边距.
请记住,#container有位置:已修复.
这里的代码演示了这个问题:[View in JSFiddle ↗]
document.getElementById('content').innerHTML = [...Array(100).keys()].join('<br>')
#container { position: fixed; background: lightblue; top: 0; bottom: 0; left: 0; right: 0; display: flex; align-items: center; justify-content: center; overflow: auto; } #content { border: 1px solid green; /* uncomment the hack below to get desired behavior */ /* margin: auto */ }
<div id="container"> <div id="content"> </div> </div>
您可以使用未注释的边距检查所需的行为:auto,问题是如何仅使用flex-属性和无边距来实现相同的结果:auto.
解决方法
如果没有标记更改,则无法使用align-items:center,如果内容超出flex容器,则设计为
overflow in both directions.
‘center’
The flex item’s margin Box is centered in the cross axis within
the line. (If the cross size of the flex line is less than that of the
flex item,it will overflow equally in both directions.)
另请注意,auto
margins在FlexBox中具有特殊含义,并且它不是黑客,恰恰相反,所以在这种情况下,它们是基于flex的解决方案来实现这一点.
document.getElementById('content').innerHTML = [...Array(100).keys()].join('<br>')
#container { position: fixed; background: lightblue; top: 0; bottom: 0; left: 0; right: 0; display: flex; overflow: auto; } #content { border: 1px solid green; margin: auto; }
<div id="container"> <div id="content"> </div> </div>