How can you horizontally center an absolutely positioned element relative to the viewport when it has a positioned parent?

Eg. how can you take the blue child in this example horizontally in relation to the viewport (i.e. in the center of the page), provided that the parent must remain the same.

Other qualifications:

  • I do not want him to be corrected.
  • Assume that the distance between the parent and the left viewport is unknown.

.parent {
  margin-left: 100px;
  margin-top: 100px;
  background: red;
  position: relative;
  width: 50px;
  height: 50px;
}

.child {
  background: blue;
  position: absolute;
  bottom: 100%;
}
<div class="parent">
  <div class="child">
    child
  </div>
</div>
Run code

I am trying to make this question SSCCE . In fact, the use case is that I have a dropup (for example, a drop-down list, expect it to appear above and not below the start button). I want the dropdown menu to be centered.

, DOM. , bottom: 100%; , .

+4
1

position:fixed , null :

body {
  transform:translate(0,0);
  min-height:150vh;
}

.parent {
  margin-left: 100px;
  margin-top: 100px;
  background: red;
  position: relative;
  width: 50px;
  height: 50px;
}

.child {
  background: blue;
  position: fixed;
  left:50%;
  transform:translate(-50%,-100%);
}
<div class="parent">
  <div class="child">
    child
  </div>
</div>
+3

Source: https://habr.com/ru/post/1694707/


All Articles