Home > other >  How to place 2 items in a flex row 1 left justified and 1 right justified
How to place 2 items in a flex row 1 left justified and 1 right justified

Time:08-06

I have 2 graphic images that I want placed into a flex row. I want the first item to left justified and the second item to be right justified. This is the code I am running:

 <div >
    
    <div >
        
       <img src="images1.png">
    
    </div>
    
    <div >
        
       <img src="images2.png">
    
    </div>
 </div>

And this is the .css that I have:

 .flex-container {
  
    display: flex;
  
    align-items: center;
  
    justify-content: center;

  }
  .flex-item {


   }
  .flex-item-left {
  
     justify-items: flex-start;
   }

It was my understanding that justify-items: flex-start would pull the item with this class to the beginning of the flex container. In my case, this should pull image1.png to the left margin. However, both images get placed in the center of the flex box.

Any assistance is greatly appreciated.

Thanks!

CodePudding user response:

You're looking for justify-content: space-between; on the flex parent.

.flex-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
<div >
  <div >
    <img src="https://dummyimage.com/200/000/fff">
  </div>
  <div >
    <img src="https://dummyimage.com/200/000/fff">
  </div>
</div>

Alternatively, you can use margin-left: auto; with flex on the parent which will do the same thing. margin: auto; will become useful when you start building more complex flex layouts.

W/ margin.

.flex-container {
  display: flex;
}

.flex-item-left {
  margin-right: auto;
}
<div >
  <div >
    <img src="https://dummyimage.com/200/000/fff">
  </div>
  <div >
    <img src="https://dummyimage.com/200/000/fff">
  </div>
</div>

CodePudding user response:

I ran your code and found out that you don't need to have the ".flex-item-left" class. Go into your ".flex-container" class and change the "justify-content: center" to "justify-content: space-between".

This is what your CSS should look like:

 .flex-container {
    display: flex;
    align-items: center;  
    justify-content: space-between;
  }
  • Related