ThiagFerreira ThiagFerreira - 16 days ago 10
CSS Question

Fixed div related to its parent

I have this snippet, but I need to make the red box be limited to the white box not transpacing.



.main {
background-color: black;
width: 100%;
height: 1250px;
position: relative;
}

.container{
display: block;
position: absolute;
width: 250px;
height: 650px;
background: white;
}

.red-box{
background: red;
width: 150px;
height: 140px;
position: fixed;
}

<div class="main">
<div class="container">
<div class="red-box">
</div>
</div>
</div>




Answer

As red-box is fixed already, make your container fixed too- hope this solves your problem. Cheers!

body {
  margin: 0;
}
.main {
  background-color: black;
  width: 100%;
  height: 1250px;
  position: relative;
}
.container {
  display: block;
  position: fixed;
  width: 250px;
  height: 650px;
  background: white;
}
.red-box {
  background: red;
  width: 150px;
  height: 140px;
  position: fixed;
}
<div class="main">
  <div class="container">
    <div class="red-box">
    </div>
  </div>
</div>

EDIT:

Hope this pins it- the red-div scrolls out along with the container using jquery:

$(document).scroll(function() {
  var wrapper = $('.container');
  var box = $('.red-box');

  var offset = wrapper.offset().top - $(window).scrollTop() + wrapper.outerHeight() - box.outerHeight();


  if (offset >= 0) {
    box.css({
      'top': 0
    });
    return;
  }

  box.offset({
    'left': box.offset().left,
    'top': $(window).scrollTop() + offset
  });


});
body {
  margin: 0;
}
.main {
  background-color: black;
  width: 100%;
  height: 1250px;
  position: relative;
}
.container {
  display: block;
  position: absolute;
  width: 250px;
  height: 650px;
  background: white;
}
.red-box {
  background: red;
  width: 150px;
  height: 140px;
  position: fixed;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
  <div class="container">
    <div class="red-box">
    </div>
  </div>
</div>

Comments