1

Let's assume we have a parent element whose dimensions are 100vh x 100vw. If that element were to have a child and that child's position was set to 'fixed'. The child would be in the center of the element

  .parent {
    height: 100vh;
    width: 100vw;
    border: solid 5px orange
  }

  .child {
    height: 6vh;
    width: 6vh;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background-color: rgba(0, 0, 0, 0.25);
    border-radius: 0.5em;
    position: fixed;
    color: steelblue;
    cursor: pointer;

    &.childOfChild { // the 3 bars
      width: 3vh;
      height: .25em;
      border-radius: .1em;
      margin: 3px;
    }
  }

enter image description here

Now let's say that the parent div's height needs to be 180vh in order to fit child elements, now because that one 'fixed' child is positioned at the center of the div. It will move down, because it's position to be at the center of the parent and not the view port.

enter image description here

So is it possible to keep the child element centered to the viewport and ignore its parent without nesting it outside of the parent? Maybe some kind of CSS positioning property? I don't want to use margins or transform properties. I want a way for the element to IGNORE it's parent's positioning without nesting it outside.

ls170292
  • 80
  • 1
  • 9
  • `position: fixed` ignores the parent element position and positions it against the viewport **except** if the parent has specific properties set: https://stackoverflow.com/questions/6794000/fixed-position-but-relative-to-container – disinfor Jan 24 '23 at 02:56
  • 1
    Note that you've misspelled "position" in your code here. I fixed the misspellings in the prose but left that one because I didn't know if that was a typo in the source, or just here on Stack Overflow. – Heretic Monkey Jan 24 '23 at 03:00
  • 1
    @HereticMonkey you might be right - looking at the devtools screenshot, OP doesn't have any elements positioned `fixed` - which if spelled incorrecty would give the impression that the child element is positioned against the parent when it wouldn't normally be. – disinfor Jan 24 '23 at 03:05
  • Sorry guys. I wrote the question in a hurry. I've edited the css code in the question to better explain the context. Either way @ksav gave me the answer I needed. I also found out the reason why my child element was always centered wwas because the parent element had, justify-content: center and align-items: center. – ls170292 Jan 24 '23 at 03:13

1 Answers1

0

body,
html {
  margin: 0;
}


.parent {
  height: 180vh;
  width: 100vw;
  background: orange;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.child {
  height: 6vh;
  width: 6vh;
  background: red;
  position: fixed;
  top: 50%;
  margin-top: -3vh;
}
<div class="parent">
  <div class="child">
  </div>
</div>
ksav
  • 20,015
  • 6
  • 46
  • 66