Dynamic positioning of elements

I have seen this thing for months and years, and I really want to know how to do it.

For example, there is an element in the middle of the page. and he is in an absolute position. When it scrolls down and reaches this element, it is fixed in position and follows scrolling, when scrolling up and back to the middle of the page becomes absolute again.

I can give the Google AdWords account page as an example, on the campaign page the headline for your keywords is the same.

how to do it?

thanks

+4
source share
2 answers

Something like this (tested on Chrome) will work:

<html> <head> <title>Example</title> <style> .banner {position: absolute; top: 40px; left: 50px; background-color:cyan} </style> <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js" /> <script type="text/javascript" > $(function() { $(window).scroll(function() { var top = $(window).scrollTop(); if (top < 40) top= 40; $('.banner').css({top: top}) }) }) </script> </head> <body> <div class="banner">This is the banner</div> <div class="content">Lorem ipsum dolor sit amet, consectetur adipiscing elit.<br/><br/><br/> Cras rhoncus euismod sagittis.<br/><br/><br/> Fusce tincidunt consectetur ante eu commodo.<br/><br/><br/> Fusce lacinia consectetur nulla sit amet mattis.<br/><br/><br/> In viverra bibendum nibh vitae pharetra.<br/><br/><br/> Nam non eros semper ipsum facilisis fringilla.<br/><br/><br/> Phasellus sit amet purus interdum arcu hendrerit sagittis.<br/><br/><br/> Sed fermentum, orci non tincidunt pellentesque, tellus ipsum ultrices dui, at venenatis mi turpis non odio.<br/><br/><br/> Etiam elementum massa eu libero molestie nec pulvinar lacus suscipit.<br/><br/><br/> Etiam erat massa, mattis et sollicitudin eu, posuere commodo ligula.<br/><br/><br/> Vestibulum nec sem arcu.<br/><br/><br/> Vestibulum justo risus, feugiat at tristique a, sagittis vel dui.<br/><br/><br/> Sed enim erat, scelerisque sit amet accumsan scelerisque, vestibulum vitae dui.<br/><br/><br/> Integer et orci enim.<br/><br/><br/> Aliquam est mauris, consequat sed egestas vitae, scelerisque non sapien.<br/><br/><br/> Nam feugiat diam eu elit dignissim commodo.<br/><br/><br/> Curabitur eleifend lacus a leo vehicula rhoncus.<br/><br/><br/> Fusce luctus antequis urna sodales vestibulum.<br/><br/><br/> Aliquam tempus nisl vitae arcu bibendum sollicitudin.<br/><br/><br/> </body> 

Edit: positioning of the 40 px element under the header, but its visibility if the user scrolls down

+3
source

you can do this with any element by applying css:

 #keepmefixed{ position:fixed; } 

however, keep in mind that IE support is not available and it does not seem to work on Safari on the iPad (from my testing). You will need to enable some JavaScript in order to make it work in these browsers.

-1
source

Source: https://habr.com/ru/post/1312744/


All Articles