Trying to center these elements

I am trying to center some elements and currently finding positioning to be the most difficult part of CSS!

I am trying to center the elements with the following classes: .box1, .box2 and .box3
I would like them to remain side by side as they are currently, but centered horizontally.

This is my code:

Also, why is .box1 to the left of the page, whereas .box2 is further towards the middle, when the CSS for them both is the same?

Thanks :slightly_smiling_face:

Wrap each list in a flex container and set the flex container to justify-content: center.

If we have understood it correctly, you aim to have 3 elements side by side but the 3 elements should be centered horizontally right?

Hoom…see if you can translate this code

The below snippet is just an example of what you are trying to achieve. Please replace as per your requirements.
I have used random tags and class names… just to demonstrate

<div class='parent'>
  <div class='box1'> box1 </div>
   <div class='box2'> box2</div>
   <div class='box3'> box3</div>
</div>

<style>
  .parent{
  display: flex; 
  justify-content: center;
}
</style>

breakdown:

  • display: flex; will align the box1,box2,box3 within the parent in a row
  • justify-content: center; will align all of those three in the center horizontally along the main axis - that is X-axis. Since by default flex aligns items in a row.

If you are finding flexbox hard, you can check out my blog - where I have tried to simplify the concept of flexbox : flexbox simplified
It is just a few mins read! :smiley:

However, @lisalittleindia, in your situation, each box class will need its own flex container.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.