skip to Main Content

I’ve been trying to figure out how to center an element within a flex box to the center of the page but I’m not sure how or if it can be done in a non-janky way. I’ve tried using absolute/relative positioning to move the elements into place but they never line up completely. I’ve have thought about using a grid and have the flex box element span the center columns but this seemed too janky as the number and size of the grid cells may not always be the same as the element I want to center.

Below I have created an example to demonstrate my problem. I am looking to center the right-most element in the flex box to the center of the page so that the blue box is at the center of the page and the red one is still to the left of it.

.title {
  text-align: center;
  font-weight: bold;
  font-size: 40;
}

.box {
  display: flex;
  margin: auto;
  justify-content: center;
}
<html>
<div class="title">
  Test Title
</div>
<div class="box">
  <div style="background-color: red; padding: 1rem;">Left Item</div>
  <div style="background-color: blue; padding: 1rem;">Right item</div>
</div>

</html>

Edit: I have created a mock up image what I want to achieve using the example I provided. Sorry if I wasn’t able to explain exactly want I wanted before.
what i want to achieve

2

Answers


  1. You can set flex-direction: column; and then give a height and a width for them.

    .title {
      text-align: center;
      font-weight: bold;
      font-size: 40;
    }
    
    .box {
      display: flex;
      margin: auto;
      flex-direction: column;
      width: 200px;
    }
    <html>
    <div class="title">
      Test Title
    </div>
    <div class="box">
      <div style="background-color: red; padding: 1rem;">Left Item</div>
      <div style="background-color: blue; padding: 1rem;">Right item</div>
    </div>
    
    </html>
      
    Login or Signup to reply.
  2. Use absolute positioning on the first div of the flex container and make it stick to the left by using left propety and settin its vlue to 0. Also, it’s really important that you set position to relative on the element you want its children absolutly positioned to, otherwise they will be psositioned absolutly to the body.

    .title {
      text-align: center;
      font-weight: bold;
      font-size: 40;
    }
    
    .box {
      position: relative;
      display: flex;
      margin: auto;
      justify-content: center;
    }
    
    .box > div:first-child {
        position: absolute;
        left: 0;
    }
    <html>
    <div class="title">
      Test Title
    </div>
    <div class="box">
      <div style="background-color: red; padding: 1rem;">Left Item</div>
      <div style="background-color: blue; padding: 1rem;">Right item</div>
    </div>
    
    </html>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search