Home > front end >  Is there a CSS position property that allows child elements to ignore their parent elements' po
Is there a CSS position property that allows child elements to ignore their parent elements' po

Time:01-24

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.

CodePudding user response:

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 >
  <div >
  </div>
</div>

  • Related