1.fixedElement {
2 background-color: #c0c0c0;
3 position:fixed;
4 top:0;
5 width:100%;
6 z-index:100;
7}
1<!DOCTYPE html>
2<html>
3
4<head>
5 <title>
6 How to make make a div stick to
7 the top of the screen once it’s
8 been scrolled to?
9 </title>
10 <style>
11 .sticky-div {
12 background-color: green;
13 position: relative;
14 width: 100%;
15 padding: 10px 0px;
16 }
17
18 .start {
19 height: 100px;
20 }
21
22 .end {
23 height: 500px;
24 }
25 </style>
26</head>
27
28<body>
29 <h1 style="color: green">
30 GeeksforGeeks
31 </h1>
32 <b>
33 How to make make a div stick
34 to the top of the screen once
35 it’s been scrolled to?
36 </b>
37 <p class="start">
38 A Computer Science portal for geeks.
39 It contains well written, well thought
40 and well explained computer science and
41 programming articles, quizzes and
42 practice/competitive programming/company
43 interview Questions.
44 </p>
45 <div class="sticky-div">
46 This is div will stick to the top when it has been scrolled past
47 </div>
48 <p class="end">
49 A Computer Science portal for geeks.
50 It contains well written, well thought
51 and well explained computer science and
52 programming articles, quizzes and
53 practice/competitive programming/company
54 interview Questions.
55 </p>
56 <script>
57 stickyElem =
58 document.querySelector(".sticky-div");
59
60 /* Gets the amount of height
61 of the element from the
62 viewport and adds the
63 pageYOffset to get the height
64 relative to the page */
65 currStickyPos =
66 stickyElem.getBoundingClientRect().top + window.pageYOffset;
67
68 window.onscroll = function() {
69
70 /* Check if the current Y offset
71 is greater than the position of
72 the element */
73 if (window.pageYOffset > currStickyPos) {
74 stickyElem.style.position = "fixed";
75 stickyElem.style.top = "0px";
76 } else {
77 stickyElem.style.position = "relative";
78 stickyElem.style.top = "initial";
79 }
80 }
81 </script>
82</body>
83
84</html>