Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (20.3k points)

How to center div horizontally, and vertically within the container using a flexbox. In the below example, I want each number below each other (in rows), which are centered horizontally.

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

http://codepen.io/anon/pen/zLxBo

1 Answer

0 votes
by (40.7k points)

Use the code given below:

html, body {

    height: 100%;

}

body {

    margin: 0;

}

.flex-container {

    height: 100%;

    padding: 0;

    margin: 0;

    display: -webkit-box;

    display: -moz-box;

    display: -ms-flexbox;

    display: -webkit-flex;

    display: flex;

    align-items: center;

    justify-content: center;

}

.row {

    width: auto;

    border: 1px solid blue;

}

.flex-item {

    background-color: tomato;

    padding: 5px;

    width: 20px;

    height: 20px;

    margin: 10px;

    line-height: 20px;

    color: white;

    font-weight: bold;

    font-size: 2em;

    text-align: center;

}

<div class="flex-container">

    <div class="row"> 

        <div class="flex-item">1</div>

        <div class="flex-item">2</div>

        <div class="flex-item">3</div>

        <div class="flex-item">4</div>

    </div>

</div>

Have a look at this demo: http://jsfiddle.net/audetwebdesign/tFscL/

If you want the height and top/bottom padding to work properly then the .flex-item elements should be block-level (div instead of span). Also, on .row, set the width to auto instead of 100%. Your .flex-container properties are fine.

Assign 100% height to HTML and body, and also zero out the body margins, if you want the .row to be centered vertically in the viewport.

Note that the .flex-container should have a height to see the vertical alignment effect, otherwise, the container will compute the minimum height needed to 

enclose the content, which will be less than the viewport height in the example.

Note: The flex-flow, flex-direction, flex-wrap properties can make this design easier to implement. The .row container will not be needed unless you want to add some styling around the elements (background image, borders and so on).

For more information, have a look at this document: http://demo.agektmr.com/flexbox/

Related questions

Browse Categories

...