0

I have a container with two elements. I want one of them to be centered horizontally, while the other one is aligned right / pushed to the right side of the container.

I tried using FlexBox and setting margin: auto; for the element that's supposed to be centered, but that makes its left and right margins exactly equal, which means it's not perfectly centerd due to the second element taking up some space (see snippet).

#container {
  display: flex;
  width: 250px;
  background-color: #2c3e50;
}

#element-1, #element-2 {
  width: 50px;
  height: 50px;
  background-color: #16a085;
}

#element-1 {
  margin: auto;
}
<div id="container">
  <div id="element-1"></div>
  <div id="element-2"></div>
</div>
RalphBear
  • 75
  • 1
  • 12

1 Answers1

0

this way ?

#container {
  width      : 250px;
  height     : 50px;
  background : darkblue;
  position   : relative;
  }
#element-1,
#element-2 {
  width      : 50px;
  height     : 50px;
  background : darkgreen;
  position   : absolute;
  top        : 0;
  }
#element-1 {
  right     : 50%;
  transform : translate(50%, 0);
  }
#element-2 {
  right     : 0;
  }
<div id="container">
  <div id="element-1"></div>
  <div id="element-2"></div>
</div>
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40