Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to create a sticky element with CSS?
On a web page, we can easily create an element that remains fixed in position when scrolling. This is achieved using the CSS position property with the value sticky.
Syntax
selector {
position: sticky;
top: value;
}
How Sticky Position Works
A sticky element toggles between relative and fixed positioning based on the user's scroll position. It sticks to the specified position when the viewport reaches the defined threshold.
Example: Creating a Sticky Header
The following example creates a sticky navigation header that remains at the top when scrolling −
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
margin: 0;
padding: 0;
height: 200vh;
}
.sticky {
position: sticky;
top: 0;
background-color: #341576;
color: white;
padding: 20px;
font-size: 18px;
text-align: center;
z-index: 100;
}
.content {
padding: 20px;
font-size: 16px;
line-height: 1.6;
}
</style>
</head>
<body>
<h1>Sticky Element Example</h1>
<p>Scroll down to see the sticky behavior</p>
<div class="sticky">This is a Sticky Header</div>
<div class="content">
<h2>Content Section</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odit vel dolore delectus esse consequatur at nulla, consequuntur sint quas ea. Incidunt, ex. Consequatur ipsa earum veritatis fugiat iusto, doloremque sunt beatae quaerat laboriosam nemo soluta quidem porro quia. Dolore reprehenderit cum voluptatibus eius assumenda ipsam tenetur asperiores magni aliquid eligendi.</p>
<p>Debitis sapiente, odit iste voluptatibus nesciunt veritatis incidunt mollitia nostrum, vitae suscipit iusto molestias consequuntur rem facere perspiciatis ad! Ratione reiciendis asperiores aperiam vitae facilis accusantium non aliquid, facere cupiditate reprehenderit tempore veritatis eum accusamus omnis tempora quos!</p>
<p>Continue scrolling to observe the sticky element behavior...</p>
</div>
</body>
</html>
A webpage with a purple sticky header that remains fixed at the top while scrolling through the content below. The header has white text and maintains its position as you scroll down the page.
Key Properties for Sticky Elements
| Property | Description |
|---|---|
position: sticky |
Makes the element sticky |
top |
Distance from top when stuck |
z-index |
Controls stacking order |
Conclusion
The position: sticky property creates elements that stick to a specified position during scrolling. It's perfect for navigation bars, headers, and sidebars that need to remain visible.
Advertisements
