RP McMurphy RP McMurphy - 5 months ago 15
CSS Question

Why isn't justify-content centering my divs?

I am trying to center two divs inside the daddy div horizontally.

Daddy div is set to

flex-direction: column
as I want the child divs one below another, but at the center of the page.

justify-content: center;
should do it but not working.

I finally made it work with
align-self
, but any explanation why this much code is not enough to center the divs inside?

Here is my code:

<div class="main">
<div class="child-1">HI</div>
<div class="child-2">WE BUILD AWESOME STUFF</div>
</div>

.main {
display: flex;
flex-direction: column;
justify-content: center;
}

Answer

Main vs Cross Axis

Consider the main axis and cross axis of a flex container:

enter image description here                                                                                                                        Source: W3C

In the image above, the main axis is horizontal and the cross axis is vertical. These are the default directions for a flex container.

However, these directions can be easily switched with the flex-direction property.

/* main axis is horizontal, cross axis is vertical */
flex-direction: row;
flex-direction: row-reverse;

/* main axis is vertical, cross axis is horizontal */    
flex-direction: column;
flex-direction: column-reverse;

(The cross axis is always perpendicular to the main axis.)


justify-content property (works on main axis only)

The justify-content property aligns flex items along the main axis of the flex container.

In other words, when your container is flex-direction: row, that makes the main axis horizontal. justify-content: center will work as you expect.

But you've set the container to flex-direction: column. This means that the main axis is now vertical, and justify-content will position flex items up/down, not left/right.

Since you have no extra height in your example, you won't notice anything different; justify-content has no space to work. (Unlike width, which block elements fill 100% by default, heights must be defined. Otherwise, elements default to auto – the height of the content.) But give the container some height and see what happens.


align-* properties (work on cross axis only)

The align-self, align-items and align-content properties operate on a flex container's cross axis (again, always perpendicular to the main axis).

Because your main axis is vertical, the align-* properties will align flex items left/right. That's why align-self worked to center your divs.


Quick Summary: Depending on the flex-direction, the main axis and cross axis switch, taking their assigned properties with them.


Solution

If your goal is minimal code, here's all you need:

.main {
    display: flex;
    flex-direction: column;
    align-items: center;
}

More details: In CSS Flexbox, why are there no "justify-items" and "justify-self" properties?