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

Tips for keeping several buttons in the spotlight: HTML/CSS/JS

Looking for a solution to keep multiple buttons toggled on? I'm not very familiar with JavaScript, but I know that adding a class on click won't work if there's already a class set. Maybe giving the element an ID could be a possible solution ...

What is the best way to create an interactive menu icon that includes dropdown options using MUI menu features?

i am looking to create a component similar to this currently, I am utilizing a material UI pop menu in my project below is the JSX code snippet <div className="navMenu" style={{ position: "relative" }}> <Tooltip title ...

Achieving overlapping of a <div> element with a "position: fixed" container while enabling vertical scrolling of the fixed container's content

In my single page application, I have a fixed container and I am trying to make one div inside this container overlap the boundaries of the fixed container while also vertically scrolling with its contents. Unfortunately, I have only been able to achieve e ...

Changing the position of an image can vary across different devices when using HTML5 Canvas

I am facing an issue with positioning a bomb image on a background city image in my project. The canvas width and height are set based on specific variables, which is causing the bomb image position to change on larger mobile screens or when zooming in. I ...

What is the best way to isolate the CSS of individual components in Angular 2?

For the first component: CSS-- ngx-dnd-container { color:black; background-color: white; } HTML- <ngx-dnd-container [model]="targetItemsA" dropZone="multiple-target-a" </ngx-dnd-container> For the sec ...

Import JSON Data into Angular-nvD3 Chart (AngularJS)

I am seeking help to load encoded JSON Data retrieved from a database via queries into an Angular-nvD3 graph. I am unsure about the best approach to achieve this task. The encoded JSON data is fetched using API queries from a database table called PRODUCT ...

Increasing the level of CSS list counters

HTML <ol> <li>item1 <ol> <li>item2</li> </ol> </li> <li>item1 <ol> <li>item2</li> <li>item3</li> </ol> </li> </ol> SC ...

What is the easiest way to modify the color of a basic PNG image in a web browser?

While working on a website project, I encountered instructions for mouseover styles in the design that got me thinking: It's straightforward to achieve with javascript or css image swapping... but here's the catch. There will be multiple icon li ...

Utilizing JavaScript Modules to Improve Decoupling of DOM Elements

Currently, I am tackling portions of a complex JavaScript application that heavily involves DOM elements. My goal is to begin modularizing the code and decoupling it. While I have come across some helpful examples, one particular issue perplexes me: should ...

The elements on the webpage are spilling over with content

I encountered an issue while creating a dashboard with a sidebar on the left side. When adding content to the page, some of it ended up hidden behind the sidebar. I tried using overflow-x:auto and this was the result: https://i.stack.imgur.com/5qHJY.jpg Be ...

Ways to prevent a div containing a lengthy content string from extending beyond other divs

Check out my Codepen project here Here is the HTML code for my personal website: <div id="splash" class="divider"> <h1 class="text-center text-uppercase">vincent/rodomista</h1> <p class="text-center text uppercase">Full Stack ...

Troubleshoot padding problems in mpdf

Note: mpdf 6.0 Greetings, In my efforts to produce precise PDFs using mpdf for future printing purposes, I have encountered an issue with the positioning of elements on the page. I require these elements to be positioned precisely from the top left corne ...

Generate a single-page PDF document mirroring the content of a website

I'm facing a dilemma. I need to generate a one-page PDF file without any gaps between the pages. Despite trying numerous plugins, add-ons, scripts, and software, all of them produce multiple pages. What I really require is to have all the pages in a s ...

What is the best way to navigate to the bottom of a page when new data is added?

I've created a chat feature in my Ionic app, but the issue is that when a user receives a new message while being on the chat screen, the view doesn't automatically scroll down to show the new message. The user has to manually scroll down to see ...

Concealing Components using Angular's ng-change Feature

I need help displaying or hiding an element in a form using ng-change or any other method you suggest. Here is the HTML snippet I am working with: <div ng-app ng-controller="Controller"> <select ng-model="myDropDown" ng-change="changeState( ...

Tips for avoiding flickering in a background image when it is being changed

Utilizing JavaScript, I am setting a repeated background image from a canvas to a div in the following way: var img_canvas = document.createElement('canvas'); img_canvas.width = 16; img_canvas.height = 16; img_canvas.getContext('2d' ...

Facing continuous 404 errors while working with nodejs and express

While attempting to collect data from a local host webpage's registration form that captures user information, I encounter an issue upon pressing the submit button A 404 Error is displayed stating "page not found", preventing the collection and out ...

Selenium - How to pass a file path to a dynamically generated input element that is not visible in the DOM

Check out this example of HTML code: This is how you create a visible button and display the selected file: <button id="visible-btn">visible button</button> <p>selected file is: <span id="selected-file"></spa ...

Update the content of a div and refresh it when a key on the keyboard is pressed

I need to hide the images in a div when I press a key on the keyboard. How can I achieve this? <div> <span role="checkbox" aria-checked="true" tabindex="0"> <img src="checked.gif" role="presentation" alt="" /> ...

CSS animation for horizontal scrolling with sticky positioning is not functioning as intended

I've designed a creative way to achieve infinite horizontal scrolling using CSS animation, and my goal is to make the first element in the list stick in place. Everything works smoothly when I utilize the left property within the @keyframes. However, ...