Home > other >  Align child element's center by the paren'ts container right edge
Align child element's center by the paren'ts container right edge

Time:12-11

Suppose, we have child element positioned at the top right corner of the parent (think of the badge over the icon button).

My problem is: I need child's center to stick to parent's right edge, but currently when badge content widen, its center shifts to the left: enter image description here

Live sandbox:

#wrapper {
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

#parent {
  width: 150px;
  height: 150px;
  background: aquamarine;
  position: relative;
}

#child {
  width: 150px;
  height: 100px;
  background: orange;
  position: absolute;
  right:  -50px;
  top: -50px;
  border-radius: 50px;
}
<div id="wrapper">
  <div id="parent">
    <div id="child"></div>
  </div>
</div>

CodePudding user response:

You can use transform: translate(50%, -50%)

#wrapper {
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

#parent {
  width: 150px;
  height: 150px;
  background: aquamarine;
  position: relative;
}

#child {
  width: 150px;
  height: 100px;
  background: orange;
  position: absolute;
  right:  0;
  top: 0;
  border-radius: 50px;
 transform: translate(50%, -50%)
}
<div id="wrapper">
  <div id="parent">
    <div id="child"></div>
  </div>
</div>

  • Related