【发布时间】:2016-06-02 09:44:31
【问题描述】:
我想将一个元素垂直和水平居中。问题是任何兄弟元素都应该保持它们相对于居中元素的位置。如果兄弟姐妹足够大,它们可能会溢出视口。兄弟姐妹的身高不同。
我在这里开始了一个代码示例:https://jsfiddle.net/hqmoz9xy/2/
html,
body {
height: 100%;
}
body {
margin: 0;
padding: 1em;
}
body,
.container {
box-sizing: border-box;
}
.container {
border: 1px solid red;
padding: 1em;
width: 100%;
height: 100%;
}
.main-display {
width: 100px;
height: 100px;
background-color: #999;
padding: 1em;
}
<div class="container">
<div class="main-display">
Main box: this box should be at the center of the container.
</div>
<ul class="extra-info">
<li>These items should naturally follow the main box and not care about vertical centering.</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</div>
这很容易使用 JS 和负边距来完成,但我只想使用 CSS 来完成。有没有办法使用 flex 做到这一点?
【问题讨论】:
-
“有没有办法使用 flex 来做到这一点?” - 不……没有。流中的任何东西都会影响它周围的元素。将其从流中取出(如绝对定位),然后居中是最合适的方法。
标签: css alignment flexbox vertical-alignment