What is causing my divs not to center with justify-content?

I've been working on centering two divs inside a parent div horizontally.

The parent div is set to flex-direction: column so that the child divs stack one below the other, but I want them centered in the middle of the page.

Although justify-content: center; should do the trick, it doesn't seem to be working for me.

I ended up getting it to work by using align-self, but I'm still wondering why such a simple approach wasn't enough to center the divs.

Take a look at 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 №1

Understanding Main Axis versus Cross Axis

Take note of the main axis and cross axis in a flex container:

In the illustration, the main axis is horizontal while the cross axis is vertical, representing the default orientations for a flex container.

However, these orientations can be interchanged using the flex-direction property.

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

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

(Note that the cross axis is always perpendicular to the main axis.)


Explanation of the justify-content Property (applicable to main axis only)

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

With the container set to flex-direction: row, resulting in a horizontal main axis, utilizing justify-content: center will align items accordingly.

Conversely, if the container has flex-direction: column defined, the main axis is now vertical, causing justify-content to position items up and down as opposed to left and right.

When there is limited height defined, the effects of justify-content may not be visible since elements default to an auto height when no specific value is provided. However, adjusting the container's height will showcase the impact.


align-* Properties (operating on cross axis exclusively)

align-self, align-items, and align-content properties affect the alignment of flex items along a flex container's cross axis, which remains perpendicular to the main axis.

Given a vertical main axis, the align-* properties will control the alignment of items from left to right. This explains why align-self was effective in centering your divs.


Key Point: Depending on the defined flex-direction, the main axis and cross axis interchange roles along with their corresponding properties.


Recommended Approach

To achieve brevity in your code, the following snippet suffices:

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

Further insights: Exploring the Absence of "justify-items" and "justify-self" Properties in CSS Flexbox

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Switching colors on SVG when hovering

When I hover over the code below, I want both eyes and eyebrows to change color. I've managed to get it working for the left eye, but not the right eye. Additionally, the fill on the right eyebrow looks strange when hovered over. I suspect this issue ...

Exploring the world of sass with compound mathematical statements

There's a slight issue that I'd like to circumvent. $var: 30px; font: 25px/25px font,font,font; //Works font: ($var - 5)/($var - 5) font, font, font; //Works not font: ($var - 5px)/($var - 5px) font, font, font; //Works no ...

Angular - Dividing Values within Input Arrays

In the input field available to users, they can enter multiple inputs separated by commas. <div class="container"> Enter your values:<input type="text" multiple #inputCheck> <input type="submit"(cli ...

Implementing a CSS codepen within a React Material-UI component

I'm struggling to implement this effect on my material ui card component using react and makeStyles. I am having difficulty translating this effect to the cards, could someone assist me in simplifying it into a CSS code that can be used in MakeStyles? ...

Is it possible to use an onclick function to input JavaScript values into a password entry box seamlessly?

Is there a way to input password values continuously using a JavaScript onclick function into a password field? I have two images, one 'Blue' and one 'Red', that trigger an onclick function with the following values: Blue= w3! Red= T4 ...

The font is displaying differently when compared to Figma

I'm currently using the font Gilroy-Bold for my project, but I'm facing inconsistencies between how it appears in Figma and my React application, even though they are both sourced from the same place. Figma: https://i.stack.imgur.com/3QvY4.png ...

anychart: The right side of Gantt Charts is being cut off or trimmed

I am utilizing anychart for my user interface. My data timelines are in epoch milliseconds. When trying to create a Gantt chart, I notice that the right side is being trimmed. Can someone please assist me with this issue? https://i.sstatic.net/H6LHk.png ...

Is the main content positioned below the sidebar on smaller screens?

In order to achieve a 250px col-2 sidebar with a col-10 main body that collapses into a top navbar and main content beneath it, my goal is set. However, I am facing an issue where the main content body goes underneath the sidebar when the screen size cha ...

Jquery plugin experiencing a malfunction

I am encountering an issue with my custom plugin as I am relatively new to this. My goal is to modify the properties of div elements on a webpage. Here is the JavaScript code I am using: (function($) { $.fn.changeDiv = function( options ) { var sett ...

Issue with jQuery not being able to retrieve the data from my CSS property

this is my custom style code: table.table tr td{ padding:30px; border-left: double 1px white; border-bottom: double 1px white; cursor:cell; } and below is the jQuery script I am using: $(document).ready(function () { ...

What is the best way to make a text scroll smoothly from left to right on my website?

I am currently working on my upcoming website and I could use some guidance in this area. My goal is to create a seamless horizontal scrolling effect on the page at a readable speed, but I'm having difficulty achieving this. *, *::after, *::before ...

Does the onChange event fire when the value is modified by the parent element?

let [number, set_number] = useState({x: 1}); <ChildComponent number={number} onUpdate={onUpdateFunction} </ChildComponent> set_number({x: 2}) After running set_number({x: 2}), will this action prompt the execution of onUpdateFunction refere ...

Can anyone help me with displaying auto complete HTML files in VScode?

As a Korean, please excuse my lack of proficiency in English. This image displays the autocomplete feature for HTML files in IntelliJ. This particular file was generated by Spring Boot (start.spring.io). How can I achieve the same in VSCode? ...

Guide to verifying a value within a JSON object in Ionic 2

Is there a way to check the value of "no_cover" in thumbnail[0] and replace it with asset/sss.jpg in order to display on the listpage? I have attempted to include <img src="{{item.LINKS.thumbnail[0]}}"> in Listpage.html, but it only shows the thumbna ...

Is the background image unable to fill up the entire screen?

I'm currently facing an issue with my webpage's background not covering the entire vertical space. Despite trying different solutions and referring to previous posts, I haven't been able to resolve it yet. Here is the relevant code: <div ...

Comparing currency to double in handlebars: a comprehensive guide

I've been working with Handlebars.js and encountered an issue when trying to compare product prices above $35. The problem arises from the fact that prices are stored as "$54.99" which gets treated as 0 when compared to a number. How can I effectively ...

Storing a Vue/JS element reference in a constant using Typescript

In my template, I have one form element and one button element: <button type="submit" id="ms_sign_in_submit" ref="submitButton" class="btn btn-lg btn-primary w-100 mb-5"> </button> Wi ...

tips for selecting various API requests based on the selected drop down menu choice

Hey there! I'm looking to enhance my login page by adding a feature that allows users to select from a dropdown menu with different options. Each option will be linked to a specific API, and based on the API response, the user's ability to log in ...

Internet Explorer 8 comes with excess padding at the top and bottom, causing un

Why is IE 8 adding unnecessary padding to a div? I have checked the styling and nothing seems out of place. Can someone assist with this issue? Html The highlighted div in blue is the main concern. .block { clear: both; } .inline { float: lef ...

Overriding a CSS property with !important proves ineffective

I need to make adjustments to an old internal page that currently has the following CSS styling: table { font-family: "Arial"; font-size: 13px; text-align: left; border-collapse: collapse; border: 1px solid black; vertical-align: m ...