Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Centering content horizontally using flexbox [duplicate]

I'm struggling to center horizontally some content in my container:

https://jsfiddle.net/y56t31q9/6/

.container {
  display: flex;
  flex-direction: column;
  width: 600px;
  background-color: blue;
  justify-content: center;
  /* Not centering content horizontally? */
}
.item {
  max-width: 500px;
  height: 100px;
  background-color: yellow;
  border: 2px solid red;
}
<div class="container">
  <div class="item"></div>
  <section class="item"></section>
  <section class="item"></section>
  <footer class="item"></footer>
</div>

I would have thought justify-content would have done the trick, but to no avail.

Any help would be greatly appreciated Thanks!

like image 385
Edwarric Avatar asked Nov 16 '16 11:11

Edwarric


People also ask

How do I center the content horizontally?

To horizontally center a block element (like <div>), use margin: auto; Setting the width of the element will prevent it from stretching out to the edges of its container.

Which property can be used to center the Flex items horizontally?

To center out item horizontally we use the justify-content: center; . The justify-content property allows us to position items along the main axis of the flex container.


3 Answers

The property justify-content:center aligns the flex-items along the flex direction - use align-items:center- see demo below:

.container {
  display: flex;
  flex-direction: column;
  width: 600px;
  background-color: blue;
  justify-content: center;
  align-items:center;/*NEW*/
}
.item {
  max-width: 500px;
  width: 250px;/*NEW*/
  height: 100px;
  background-color: yellow;
  border: 2px solid red;
}
<div class="container">
  <div class="item"></div>
  <section class="item"></section>
  <section class="item"></section>
  <footer class="item"></footer>
</div>

Refer: Flexbox W3C spec

Below is an image that applies when flex-direction is row:

image

a. Main axis alignment : justify-content

b. Cross axis alignment : align-items

When the flex-direction is row, the main-axis is horizontal but when it is column, it is the other way around.

like image 79
kukkuz Avatar answered Oct 23 '22 22:10

kukkuz


Add align-items:center;

.container {
  display: flex;
  flex-direction: column;
  width: 600px;
  background-color: blue;
  justify-content: center; 
  align-items:center;
}
like image 26
El0din Avatar answered Oct 23 '22 22:10

El0din


Remove flex-direction:column and max-width:500px. Give some fixed width say 100px and it will work properly. If you are using flex-direction:column use align-items:center property to horizontally center and justify-center if it is row.

like image 29
Mr.Pandya Avatar answered Oct 24 '22 00:10

Mr.Pandya