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

Asked

Viewed 284 times

6

I need a div to be fixed on the screen, IE, descend as I visualize the rest of the page, but the problem with the position:fixed is that it takes the element of page flow.

I want this div to be fixed within the boundaries 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: https://developers.google.com/speed/pagespeed/insights/? url=www.google.com

Note 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? Can I use jQuery.

  • 1

    You have to have 3 div. One relative, within a fixed and inside another relative. The first div that is the master goes as far as you determine, 100% maybe. The second is fixed, will scroll next to the page. And the third div that is inside the fixed, will accompany along...

  • Here’s an example I did: https://jsfiddle.net/s9jvxvpd/

  • try to put display: block on that div.

  • 1

    The problem, Diego, is that I want her to stop when she reaches the other div’s limits, this one will be positioned normally on the page. Look at the example I posted in the question, from google. If you inspect the element, you will see that when the image "hits" at the end of the div, a top which increases as I scroll the page, which is probably controlled by a script.

3 answers

1


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

Can be seen here too: http://codepen.io/anon/pen/XbwaRB?editors=010

Explaining:

  • The names of the variables already explain so I won’t even comment.

  • First I put inside the onload the scroll event, I believe I could do with Eventlistener too, but preferred so.

  • Within the function that is called with the scroll of the page I created a conditional that will do all the magic.

  • The first condition asks if the amount of scroll so far added to the height of the lateral div is equal to the lower limit of the content div, which indicates that it has reached the end of the content, this makes it stop rolling.

  • The second condition checks if the scroll is between the upper limit and the lower limit of the content div, and then sets the lateral div fixed.

  • Should you arrive at Else means that you rolled the page up beyond the upper limit of the content, or rolled over, and makes the side div stop rolling and stand at the top of the content div.

Important:

I used position="Absolute" to make div position herself by taking her father as a reference, it is important that div pai has position="relative" or "Absolute", otherwise it won’t 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>

1

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

The always excellent css-Tricks has a nice tutorial on how to do this. This thumb drive user’s simpleminded also illustrates the concept. And finally, an example navigation.

1

I made an example here that maybe is 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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.