Search code examples
csscenterflexbox

Flexbox, center several elements vertically (as one)


I have a container with several elements inside. I want to center these elements vertically, as a group. Can this be done with flexbox and if so, how?

Here is a demo:

.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>


Solution

  • You just need justify-content:center;

    fiddle: 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;
    }