Fixed Position
You may have noticed that an element with absolute position (position: absolute;
) is ignored by other elements and moves along with the page when scrolling.
What if we want an element to stay in the same place even when scrolling? We use fixed position (position: fixed;
).
.navbar {
position: fixed;
left: 0px;
top: 0px;
}
This would fix the element with the class navbar
to the top left of the screen regardless of scrolling.
Fixed position is commonly used for navigation bars at the top of a web page to ensure visibility regardless of page scrolling.
Instructions
Try scrolling up and down the page and notice that the red square moves along with the page just like the other elements. After trying, click Run.
Change the position of the element with id square2 (#square2
) from absolute to fixed, leaving everything else the same.
Now try scrolling the page and notice that the red square stays in the same position on the screen regardless of scrolling.
Start programming for free
8/10