htmlcssflexboxcss-selectorsjustify

Why won't justify-content: center move the h2 and #experience_content items to the center of the .experience box?


<html>
<head>
<style>
.experience {
    display: flex;
    flex-direction: column;
    justify-content: center;

}

.experience h2 {
    
}

#experience_content {
    display: flex;
    gap: 10px;

}
</style>
</head>
<body>

    <section class="experience">
            
        <h2>Work Experience</h2>
            
        <div id="experience_content">
            <img src=./images/supermarket.jpg width="260" height="195" alt=" shopping center">
                    
        <p> Please help me solve this stupid problem. I beg you.</p>
        </div>

    </section>

</body>
</html>

I tried removing the h2 element from the .experience element.

I tried justify-content: center on the #experience_content element, and that didn't work for the img and p elements either.


Solution

  • The issue you're facing is because you're applying justify-content: center to a flex container with flex-direction: column. The justify-content property works along the main-axis of the flex container, which, in this case, is the vertical axis due to flex-direction: column. If you want horizontal centering, you'll need to use the property that works on the cross-axis which is align-items.

    <html>
    
    <head>
      <style>
        .experience {
          display: flex;
          flex-direction: column;
          align-items: center;
          /* <-- Here */
        }
        
        .experience h2 {}
        
        #experience_content {
          gap: 10px;
        }
      </style>
    </head>
    
    <body>
    
      <section class="experience">
    
        <h2>Work Experience</h2>
    
        <div id="experience_content">
          <img src=./images/supermarket.jpg width="260" height="195" alt=" shopping center">
    
          <p> Please help me solve this stupid problem. I beg you.</p>
        </div>
    
      </section>
    
    </body>
    
    </html>