Search code examples
htmlcssflexbox

Using Flex to position one button center, and the second flex-end


I have two buttons in a container. One should display centrally, the second should be always positioned on the right.

However, the button-right is not always visible in the DOM, in which case then the button-center then aligns to the right.

Is it possible to avoid using margin-left: auto and instead using flex properties so that the elements are always positioned in the desired locations, regardless of the presence of each other?

I tried using justify-content: center and justify-content: flex-end but that didn't help.

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

.container .button-center {
  display: flex;
  margin-left: auto;
}

.container .button-right {
  margin-left: auto;
}
<div class="container">
  <button class="button-center">Centered Button</button>
  <button class="button-right">Right Button</button>
</div>


Solution

  • Try this. Put a container around each button. The containers are 1/3 of the width and they are aligned towards the end of the container.

    Each container is also a flex container, one with center justified content, the other with end justified content.

    I put a border on the button containers to help visualize what is going on.

    .container {
      display: flex;
      justify-content: end;
    }
    
    .container .button-center,
    .container .button-right {
      border: 1px solid #CCC;
      width: 33.333%;
      display: flex;
    }
    
    .container .button-center {
      justify-content: center;
    }
    
    .container .button-right {
      justify-content: end;
    }
    <div class="container">
      <div class="button-center">
        <button>Centered Button</button>
      </div>
      <div class="button-right">
        <button>Right Button</button>
      </div>
    </div>