Flexbox,垂直居中几个元素(作为一个)

时间:2015-09-22 15:16:09

标签: css center flexbox

我有一个容器里面有几个元素。我希望将这些元素作为一个组垂直居中。这可以用flexbox完成,如果可以,怎么做?

这是一个演示:

.container {
  margin: 0 auto;
  width: 700px;
  height: 600px;
  background: #ebebeb;
  flex-direction: column;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  -ms-flex-align: center;
  -webkit-align-items: center;
  -webkit-box-align: center;
  align-items: center;
}

.btn {
    display: inline-block;
    padding: 5px 10px;
    padding: 0.3125rem 0.625rem;
    background: #129c87;
    color: #fff;
    border: 1px solid #999;
    border-radius: 2px;
    font-weight: 600;
    text-align: center;
    outline: none;
    border: none;
    cursor: pointer;
    font-family: Arial;
  }
<div class="container">
  
  <h1>Center me and my paragraphs plz</h1>
  <p>First paragraph is always first</p>
  <p>Then comes the second</p>
  <a class="btn" href="#">Read more</a>
  
</div>

1 个答案:

答案 0 :(得分:3)

您只需要justify-content:center;

小提琴:https://jsfiddle.net/w64ks4x7/

.container {
  margin: 0 auto;
  width: 700px;
  height: 600px;
  background: #ebebeb;
  flex-direction: column;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  -ms-flex-align: center;
  -webkit-align-items: center;
  -webkit-box-align: center;
  align-items: center;
    justify-content:center;
}