Home > Software design >  How to place absolute positioned element outside of relative parent CSS
How to place absolute positioned element outside of relative parent CSS

Time:06-11

<div >
    <div >
    </div>
</div>

<style>
.parent {
    height: 500px;
    width: 500px;
    background: red;
    margin: 0 auto;
    position: relative;
    
}

.child {
    height: 200px;
    width: 200px;
    background: green;
    position: absolute;
    left: 0;
}

</style>

I need green box to go outside of red box, it needs to be stuck on left of screen always. Is it possible with css? without using .parent {position: unset;} or something like that.

enter image description here

CodePudding user response:

If you want to position the child element based on the viewport then use position: fixed; instead of position: absolute; -- hover anywhere in the snippet below to see the parent move while the child stays in the same place on the left of the screen

body { height: 100vh; margin: 0; display: grid; place-items: center; }



.parent {
  height: 50vh;
  width: 50vw;
  background: red;
  position: relative;
  left: 0;
  top: 0;
  
  transition: all 500ms 0ms ease-in-out;
}
.child {
  height: 25vh;
  width: 25vw;
  background: green;
  
  position: fixed;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
}

body:hover .parent {
  left: 50vw;
  top: 50vh;
}
<div >
  <div ></div>
</div>

CodePudding user response:

Based on a comment from OP this answer is no longer appropriate but it still valid based on how the question is worded

You can do it with position: absolute; by putting in a negative value, or a value greater the the size of the parent. Otherwise it can be done with transform: translate( [X]px, [Y]px ); and it works much like position absolute but is better for performance!

body { margin: 0 }




.parent {
  height: 300px;
  width: 300px;
  background: red;
  margin: 100px auto 0;
}
.child {
  height: 100px;
  width: 100px;
  background: green;
  color: white;
  opacity: 0.75;
  
  line-height: 100px;
  text-align: center;
}

.parent1 {
  position: relative;
}

.parent1 .child {
  position: absolute;
  left: -50px;
  top: -50px;
}

.parent2 {}

.parent2 .child {
    transform: translate(-50px, -50px);
}
<div >
    <div >
      Position
    </div>
</div>
<div >
    <div >
      Transform
    </div>
</div>

  • Related