Div with fixed position on the screen within the limits of another div

6

I need a div to be fixed on the screen, ie, go down as I see the rest of the page, but the problem with position:fixed is that it takes the element out of the page flow.

I want this div to be fixed within the bounds of another div, and I know I'll have to use javascript, I've tried some solutions, but none really worked.

The best example I can give is this on the google speed test page: link

Notice how the mobile and desktop preview are fixed on the screen, but when I get to the footer they "brake" and stay on top. Any guidance on how I can do this? I can use jQuery.

    
asked by anonymous 17.08.2015 / 19:34

3 answers

1

Below is the code I made, imitating what happens in the example you sent.

It can also be seen here: link

Explaining:

  • Variable names already explain then nor will I comment.

  • First I put the scroll event onload, I believe I could do it with EventListener too, but I preferred it.

  • The first condition asks if the amount of scroll hitherto added to the height of the side div is equal to the lower limit of the content div, which indicates that it has reached the end of the content, so that it stops scrolling.

  • The second condition checks whether the scroll is between the upper bound and the lower bound of the content div, and then places the fixed side div.

  • If you reach the else it means that you rolled the page up beyond the top of the content boundary, or rolled, and the side div stops scrolling and is positioned at the top of the page div of content.

Important:

I used position="absolute" to make the div position by taking its parent div as a reference, it is important that the parent div has position="relative" in> "absolute" , otherwise it will not work.

window.onload = function() {
  var global = document.querySelector("#global");
  var aoLado = document.querySelector("#aoLado");

  window.onscroll = function() {

    if (document.body.scrollTop + aoLado.offsetHeight >= global.offsetTop + global.offsetHeight) {
      aoLado.removeAttribute("style");
      aoLado.style.position = "absolute";
      aoLado.style.top = global.offsetHeight - aoLado.offsetHeight + "px";
    } else if (document.body.scrollTop >= global.offsetTop && document.body.scrollTop <= global.offsetTop + global.offsetHeight) {
      aoLado.style.position = "fixed";
      aoLado.style.top = "0";
    } else {
      aoLado.style.position = "absolute";
      aoLado.style.top = "0";
    }

  }
}
* {
  margin: 0;
  padding: 0;
}
header {
  width: 100%;
  height: 200px;
  background: #ccc;
}
footer {
  width: 100%;
  height: 500px;
  background: #ccc;
}
#global {
  position: relative;
  width: 100%;
  height: auto;
}
#conteudo {
  position: relative;
  padding: 10px;
  width: 60%;
  text-align: justify;
  border: 1px solid #999;
  box-sizing: border-box;
}
#aoLado {
  position: absolute;
  right: 0;
  top: 0;
  padding: 10px;
  width: 40%;
  box-sizing: border-box;
  text-align: justify;
  border: 1px solid #999;
  text-align: center;
}
#aoLado img {
  height: 300px;
  max-width: 100%;
}
<header></header>
<section id="global">
  <article id="conteudo">
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It
      has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer
      took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset
      sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the
      industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially
      unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy
      text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five
      centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like
      Aldus PageMaker including versions of Lorem Ipsum.</p>
  </article>
  <aside id="aoLado">
    <img src="http://pngimg.com/upload/iphone_PNG5729.png" />
  </aside>
</section>
<footer></footer>
    
18.08.2015 / 15:21
1

This concept is called "Scroll then fix". It's relatively easy to do.

The always excellent css-tricks has a nice tutorial on how to do this. This pen of the user simpleminded also illustrates the concept. And finally, a navigation example .

    
18.08.2015 / 15:21
1

I've made an example here that may be what you want.

var header = document.querySelector("header");
var footer = document.querySelector("footer");
var bloco = document.querySelector("#bloco");

var onScroll = function (event) {
  var scrollY = Math.round(window.pageYOffset);
  var offsetTop = scrollY - header.offsetHeight;
  var offsetBottom = scrollY + bloco.offsetHeight + footer.offsetHeight + 40;

  console.log(offsetBottom, document.body.scrollHeight);

  if (offsetBottom > document.body.scrollHeight) {    
    console.log("Hello World");
    bloco.style.top = null;
    bloco.style.bottom = "20px";
  } else if (offsetTop > 0){
    bloco.style.top = (offsetTop + 20) + "px";
    bloco.style.bottom = null;
  } else {
    bloco.style.top = "20px";
    bloco.style.bottom = null;
  }
}

document.addEventListener("scroll", onScroll);
onScroll();
body {
  position: absolute;
  min-height: 100%;
  padding: 0px;
  margin: 0px;
  left: 0px;
  right: 0px;
  height: auto;
}

header, footer {
  position: absolute;
  background-color: gainsboro;
  box-shadow: 0px 0px 10px black;
  left: 0px;
  right: 0px;

}

header {
  top: 0px;
  height: 100px;  
}

footer {    
  bottom: 0px;
  height: 300px;  
}

section {
  width: 100%;
  min-height: 100%;
  box-sizing: border-box;
  padding: 100px 0px 300px 0px;
}

section .esquerda {
  padding-right: 100px;
}

section .direita {
  position: absolute;
  top: 100px;
  right: 0px;
  bottom: 300px;
  width: 100px;    
}

#lipsum {
  display: block;
}

#bloco {
  position: absolute;
  background-color: gainsboro;
  left: 20px;
  right: 20px;
  height: 300px;
  box-shadow: 0px 0px 10px black;
}
<header>

</header>
<section>
  <div class="esquerda">
    <div id="lipsum">
      <p>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse fermentum nec ex nec maximus. Proin nec placerat purus. Cras pretium luctus congue. Quisque in pretium elit, in condimentum eros. Sed elementum nisi ac nulla lacinia malesuada. Pellentesque at luctus orci. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nunc placerat, neque id imperdiet malesuada, risus elit viverra neque, at mollis felis lectus sed ex. Integer scelerisque venenatis ante, tempor finibus tortor laoreet eu. Mauris dignissim consectetur congue. Donec vestibulum, enim finibus accumsan accumsan, quam nisl scelerisque nibh, vel semper sem sapien dignissim metus. Phasellus vel nisl in felis ornare gravida non ut odio.
      </p>
      <p>
        Aliquam erat volutpat. Nam convallis ante eget commodo lobortis. Donec pharetra risus id aliquet interdum. Suspendisse potenti. Ut et eros purus. Sed et vestibulum nisi. Phasellus convallis, risus vel ultrices porttitor, est sapien sollicitudin nulla, et iaculis justo metus non nisl. Proin blandit, nunc eget consectetur accumsan, lacus libero semper libero, vel sodales felis lacus ut mi.
      </p>
      <p>
        Mauris posuere rhoncus vestibulum. Mauris et tellus sit amet dolor vehicula lobortis quis at sem. Aliquam maximus porta augue. Ut tincidunt sollicitudin orci non maximus. Integer turpis sem, scelerisque sit amet rhoncus sed, elementum sit amet nisi. Nam ultricies et arcu ac maximus. Aliquam risus risus, placerat ac leo vulputate, feugiat interdum leo. Integer posuere sem quis ligula elementum tincidunt. Etiam ac ligula a elit faucibus ullamcorper. Morbi varius tempor tortor sed commodo. Mauris tristique, velit nec porta interdum, purus ex sagittis odio, a dapibus quam sem non dolor. Pellentesque finibus ligula non orci iaculis laoreet. Morbi molestie mollis erat, eget venenatis tellus pellentesque at.
      </p>
      <p>
        Donec at eros eu nisl blandit feugiat quis at velit. Etiam purus tellus, pellentesque at cursus a, finibus ut ipsum. Duis luctus tempor neque id pharetra. Duis interdum at sem at tincidunt. Donec auctor ante libero, eget aliquet lorem vestibulum a. Proin non sapien ultricies ligula facilisis lobortis vel ac lorem. Morbi tristique finibus purus, sed aliquet ante.
      </p>
      <p>
        Nullam pharetra fermentum purus a aliquam. Morbi dictum rutrum ex, sed accumsan purus. Vestibulum convallis dui eget purus cursus gravida. Morbi interdum dapibus turpis eu blandit. Donec semper nunc nibh, id dictum leo suscipit non. Nam facilisis tincidunt porttitor. Aliquam elementum nisi non tortor elementum, et tempus nunc mattis. Duis consequat condimentum elit nec scelerisque. Cras ut rutrum mauris.
      </p>
      <p>
        Vestibulum et nulla non lorem faucibus pellentesque. Phasellus at libero nec odio rhoncus aliquet vel eget eros. Quisque iaculis turpis mauris, vitae luctus enim elementum ut. Ut sollicitudin, mi vitae feugiat fringilla, est elit blandit risus, a porttitor eros nulla eget tellus. Morbi tempus, mauris quis suscipit volutpat, velit nibh sodales nibh, sollicitudin ullamcorper quam purus at leo. Cras ac quam quis libero mollis bibendum. Maecenas a scelerisque orci, et faucibus nulla. Curabitur egestas velit lorem, ut condimentum ipsum fermentum vitae. Aliquam ac maximus augue. Nunc consequat a magna a finibus. Vestibulum lorem diam, congue id orci sed, molestie pharetra lacus. Aliquam urna ex, varius in semper non, mattis vitae tortor.
      </p>
      <p>
        Donec sit amet feugiat neque. Donec libero orci, dignissim id lectus eget, ultrices feugiat lacus. Aliquam dapibus hendrerit lectus ut hendrerit. Fusce vulputate velit vel risus elementum interdum. Etiam rhoncus iaculis orci, non accumsan enim ultricies at. Etiam ultrices, velit et tempor rhoncus, mi nisi porttitor dolor, eu sodales quam magna sit amet nisi. Curabitur mollis ligula eu interdum varius. Integer nibh nulla, auctor non nulla et, fermentum efficitur turpis.
      </p>
      <p>
        Pellentesque et purus a dolor gravida tristique et id nulla. Maecenas euismod ex quis enim varius, in commodo ipsum fermentum. Maecenas molestie in metus eget hendrerit. Cras augue nibh, volutpat nec ante eget, hendrerit ornare odio. Donec quis pretium enim. Proin congue augue libero, eu tincidunt sem ultricies non. Morbi a metus ac magna vehicula congue.
      </p>
      <p>
        In convallis in velit ac ultricies. Praesent ac accumsan justo. Donec libero est, placerat eget cursus sed, fringilla vitae lectus. Suspendisse condimentum elementum metus, id pulvinar risus sagittis ac. Proin commodo bibendum neque molestie viverra. Phasellus efficitur nisi in urna iaculis fermentum. Aliquam eget varius neque. Nunc facilisis luctus arcu ac faucibus. Vivamus finibus, mi a vehicula suscipit, enim nisl efficitur erat, eu pellentesque justo purus vel leo. In libero massa, iaculis ut convallis id, pellentesque et lorem. Nullam consequat quam elit, a hendrerit arcu tristique ac. Mauris at egestas eros. Pellentesque sollicitudin libero ut leo porta viverra. Ut fringilla feugiat justo, vitae rhoncus ex porttitor ut. Morbi dapibus fringilla sapien imperdiet euismod. Nunc faucibus, ante et elementum porta, arcu ligula tincidunt magna, ut blandit ligula mi eget urna.
      </p>
      <p>
        Nunc venenatis est ut odio porttitor luctus. Nam dignissim eros vel leo dapibus, eget accumsan neque consequat. Nunc hendrerit nisi mattis facilisis venenatis. Vivamus aliquam quam eu dapibus mollis. Vivamus malesuada ullamcorper odio, id vestibulum urna vehicula ut. Proin condimentum nibh lectus, quis bibendum ligula lobortis non. Morbi auctor accumsan ipsum vitae scelerisque. Vivamus lacinia ante id facilisis pretium. Nulla lorem lectus, egestas sit amet lorem id, tincidunt semper risus. Integer tempus tellus et velit ultrices, sed ultricies eros facilisis. Vivamus interdum nibh at purus semper laoreet. Sed varius, nisi vitae ultricies ultrices, ligula nulla dignissim tortor, in tristique turpis enim quis nulla. Nullam pulvinar pharetra justo ut posuere.
      </p>
      <p>
        Morbi et dignissim libero. Morbi ultricies in mauris tincidunt euismod. Pellentesque id posuere ante. Sed lobortis elementum turpis. In hac habitasse platea dictumst. Curabitur cursus turpis ligula, eget rhoncus quam mollis at. Suspendisse elementum ac quam id faucibus.
      </p>
      <p>
        Integer eget mauris a dolor aliquet placerat. Nam nisi tellus, tristique nec luctus in, pulvinar nec ex. Praesent varius diam non iaculis finibus. Quisque tempor pulvinar leo, non ultricies dolor varius eget. Mauris placerat metus nibh, vel imperdiet velit consectetur in. Maecenas sit amet neque non lorem porttitor molestie. Phasellus placerat sem a neque sollicitudin dictum. Quisque vestibulum erat dui, at gravida est ultrices at. Etiam vel scelerisque eros. Nunc maximus lacus et massa malesuada dignissim. Integer iaculis elit quis velit posuere, sit amet aliquet ante bibendum.
      </p>
      <p>
        Suspendisse ullamcorper, eros vitae lobortis egestas, tortor velit eleifend mauris, eget aliquam metus purus sit amet dolor. Sed scelerisque vel diam in dignissim. Suspendisse ullamcorper fermentum ipsum sed sodales. Mauris quis mattis elit. Sed quam nisi, malesuada sit amet ultrices sit amet, auctor eget nulla. Praesent varius purus sem, nec pharetra lacus pellentesque vitae. Vestibulum laoreet purus quis enim finibus, nec porttitor nisl dictum. Phasellus placerat dui turpis. Proin auctor lorem ac neque semper, eget feugiat nisi viverra. Praesent a pretium urna. Maecenas commodo erat metus, et mollis turpis aliquet non. Curabitur ultrices consectetur egestas. Vivamus suscipit dolor vel massa posuere auctor. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos.
      </p>
      <p>
        Donec quis facilisis ex. Nam tincidunt auctor metus, tempus porta leo vehicula vitae. Cras facilisis sed enim ut rutrum. Aliquam et turpis urna. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Sed tincidunt porta consectetur. Aliquam eget nisl non turpis commodo vehicula. Nulla condimentum, nibh quis pellentesque ullamcorper, diam risus ultricies orci, at lacinia ipsum turpis non eros. Etiam ut lacus tristique, posuere ex vitae, hendrerit ex.
      </p>
      <p>
        Duis vel fringilla turpis. Etiam ante felis, tempor nec lectus eu, tincidunt consectetur mi. Donec metus quam, condimentum at malesuada et, feugiat ac leo. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla sed elementum lorem. Morbi blandit aliquam rhoncus. Praesent nunc tortor, pellentesque vel urna imperdiet, faucibus pellentesque mi. Sed eu fringilla urna. Phasellus tristique urna a mi viverra, id dictum est feugiat. Maecenas ac nibh sed risus congue rhoncus eget a purus. Duis diam elit, dapibus at semper quis, facilisis ac neque. Nunc sagittis, enim quis accumsan ultricies, diam nibh dignissim tellus, eget luctus erat risus dapibus leo. Nullam id tempus lorem. Aliquam laoreet est sapien, in tempus erat lacinia in. Aenean eu commodo diam.
      </p>
    </div>
  </div>
  <div class="direita">
    <div id="bloco">
    </div>
  </div>
</section>
<footer>

</footer>
    
18.08.2015 / 16:44