0

I need to center(left to right) absolute elements(green) inside a relative container(blue). The child elements(green) need to have a dynamic/unset width. I would rather not use JavaScript(CSS and html only).

enter image description here

Code:

.relativeParent {
  width: 100px;
  height: 100px;
  background: blue;
  position: relative;
  overflow: visible;
  display: block;
  margin-left: 100px;
  margin-bottom: 20px;
}

.absoluteChild {
  display: block;
  background: green;
  position: absolute;
}
<div class="App">
  <div class='relativeParent'>
    <div class='absoluteChild'>test</div>
  </div>
  <div class='relativeParent'>
    <div class='absoluteChild'>asd asdf asdf asdf asdfa sdf</div>
  </div>
</div>
tanner burton
  • 1,049
  • 13
  • 14
  • My solution for this was this ```transform: translate(calc(-50% + 50px) , 0);```. This only works because I assume the with of the parent will be 100px and not change. – tanner burton Oct 07 '20 at 18:12

1 Answers1

0

Add left: 50%;top: 50%;transform: translate(-50%, -50%); to absolute div.

.relativeParent {
  width: 100px;
  height: 100px;
  background: blue;
  position: relative;
  overflow: visible;
  display: block;
  margin-bottom: 20px;
}

.absoluteChild {
  display: block;
  width: 100%;
  background: green;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

.flexParent {
  background: green;
  display: flex;
  flex-wrap: wrap;
  width: 100px;
  min-height: 100px;
  justify-content: center;
  align-items: center;
  padding: 12px 0;
}

.flexParent .child {
  background: blue;
  padding: 8px;
}
<div class="App">
  <div class='relativeParent'>
    <div class='absoluteChild'>test</div>
  </div>
  <div class='relativeParent'>
    <div class='absoluteChild'>asd asdf asdf asdf asdfa sdf</div>
  </div>
  <div class='flexParent'>
    <div class='child'>asd asdf asdf asdf asdfa sdf asd asdf asdf asdf asdfa sdfasd asdf asdf asdf asdfa sdfasd asdf asdf asdf asdfa sdfasd asdf asdf asdf asdfa sdf</div>
  </div>
</div>
Rohit Utekar
  • 828
  • 5
  • 10
  • The only problem is the green cannot fill the width of the blue container. This is probably why you increased the width of the blue box to 200px. – tanner burton Oct 05 '20 at 18:52
  • I have modified the code. Please check. If you think the content of child div can be more parent, then you will have to set parent div using javascript. In that case, the best option will be to `display: flex;`, I have added the sample code in answer – Rohit Utekar Oct 06 '20 at 02:07
  • Now "test" does not have dynamic width. I think you see the issue. This ended up working for me. transform: translate(calc(-50% + 50px) , 0); – tanner burton Oct 06 '20 at 14:48