Flexbox:水平方向和垂直方向居中
如何使用flexbox将div水平居中,并在容器内垂直居中。在下面的例子中,我希望每个数字都在彼此的下面(以行为单位),水平居中。
.flex-container {
padding: 0;
margin: 0;
list-style: none;
display: flex;
align-items: center;
justify-content: center;
}
row {
width: 100%;
}
.flex-item {
background: tomato;
padding: 5px;
width: 200px;
height: 150px;
margin: 10px;
line-height: 150px;
color: white;
font-weight: bold;
font-size: 3em;
text-align: center;
}
<div class="flex-container">
<div class="row">
<span class="flex-item">1</span>
</div>
<div class="row">
<span class="flex-item">2</span>
</div>
<div class="row">
<span class="flex-item">3</span>
</div>
<div class="row">
<span class="flex-item">4</span>
</div>
</div>
<!--结束片段-->。
579
10
我认为你要的是类似以下的东西。
如何在Flexbox中使元素垂直和水平居中
以下是两种通用的居中解决方案。
一个是垂直对齐的柔性项目(
flex-direction: column
),另一个是水平对齐的柔性项目(flex-direction: row
)。在这两种情况下,居中的Divs的高度可以是可变的、未定义的、未知的,等等。居中的Divs的高度并不重要。
以下是两种情况的HTML:。
CSS (不包括装饰性样式)
当柔性项目被垂直堆叠时:。
[![在此输入图片描述][2]][2] 。
[DEMO](http://jsfiddle.net/8o29y7pd/)
当柔性项目被水平堆叠时:。
调整上述代码中的
flex-direction
规则。[![在此输入图片描述][3]][3] 。
[DEMO](http://jsfiddle.net/8o29y7pd/3/)
柔性项目的内容居中
添加
到任何你想居中的容器元素。 文档。 justify-content]1和 [align-items][2].
1:
[2]: https://developer.mozilla.org/de/docs/Web/CSS/align-items
不要忘记使用重要的浏览器特定属性。
align-items: center; -->
justify-content: center; -->
你可以阅读这两个链接,以便更好地理解柔性。 http://css-tricks.com/almanac/properties/j/justify-content/ 和 http://ptb2.me/flexbox/
好运。
1 - 在父div上设置CSS为
display.flex;
。 flex;`
2 - 在父 div 上设置 CSS 为 "flex-direction.column;
<br>"。 列;
注意,这将使该div内的所有内容从上到下排列。 如果父 div 只包含子 div,而没有其他内容,这将发挥最佳效果。<br>。
3 - 在父div上设置CSS为
justify-content: center;
下面是一个CSS的例子。
<!--开始片段。 js hide: false console.true babel: true true babel.false --> -- begin snippet: js hide: false console: true false -->
<!--结束片段-->
diplay.flex;
for it's container andmargin:auto;
for it's item works perfect: flex;为它的容器和
margin:auto;`为它的项目工作完美。注意:你必须设置 "width "和 "height "才能看到效果。
<!--开始片段。 js hide: false console: true babel.false --> -- begin snippet: js hide: false console: true false -->
<!--结束片段-->
margin: auto
与flexbox完美结合。 它在垂直和水平方向集中。<!--开始片段。 js hide: false console.true babel: true true babel.false --> -- begin snippet: js hide: false console: true false -->
<!--结束片段-->
如果你需要在链接中把文字居中,这就可以做到。
<!--开始片段。 js hide: false console: true babel.false --> -- begin snippet: js hide: false console: true false -->
<!--结束片段-->
您可以利用
display: flex; align-items: 居中。 justify-content.center;
display: flex; align-items: center; justify-content: center;`在您的父组件上
[![在此输入图像描述][1]][1] https://repl.it/repls/TomatoImaginaryInitialization
[1]: https://i.stack.imgur.com/sBAyt.png
使用[CSS+][1]
看一看[这里][2]
[1]: http://www.css.plus [2]: http://codepen.io/hicTech/pen/emvMBw