skip to Main Content

I’m using CSS Flexbox to create a layout with multiple child elements. However, I’m encountering an issue where the child elements are not aligning properly within the parent container. I want them to be evenly distributed and centered horizontally, but they appear misaligned or with unequal spacing.

My code is:

<div class="parent">
  <div class="child">box 1</div>
  <div class="child">box 2</div>
  <div class="child">box 3</div>
</div>

.parent{
  display: flex;
  justify-content: center;
}

.child{
  margin: 10px;
  padding: 10px;
  background-color: #ccc;
}

What could be causing this issue? How can I ensure that the child elements are evenly distributed and centered within the parent container using CSS Flexbox? Give Any insights or suggestions Please.

Creating space on the left side and evenly distributing any remaining space between the elements. The expected outcome is that the child elements should be evenly distributed and centered both horizontally and vertically within the parent container.

3

Answers


  1. /* Distributed alignment /
    justify-content: space-between; /
    Distribute items evenly
    The first item is flush with the start,
    the last is flush with the end */
    enter code here

    justify-content: space-around; /* Distribute items evenly
    Items have a half-size space
    on either end */
    enter code here

    justify-content: space-evenly; /* Distribute items evenly
    Items have equal space around them */
    enter code here

    You should checkout MDN for more flex justify properties here – https://developer.mozilla.org/en-US/docs/Web/CSS/justify-content

    Login or Signup to reply.
  2. I think you want to center child item horizontally and vertically with equal space between then align in center. Here is code you can try this.

    .parent{
      display: flex;
      justify-content: center;
      align-item: center;
      gap: 1rem; /* Adjust according to your need*/
    }
    
    .child{
      margin: 10px;
      padding: 10px;
      background-color: #ccc;
    }
      <div class="parent">
         <div class="child">box 1</div>
         <div class="child">box 2</div>
         <div class="child">box 3</div>
      </div>
    Login or Signup to reply.
  3. just add align-items to parent:

    .parent{
      display: flex;
      justify-content: center;
      align-items:center;
    }
    
    .child{
      margin: 10px;
      padding: 10px;
      background-color: #ccc;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search