Examples of Bootstrap 5 Position Sticky Top
Example 1: In this example, we will create a div element of fixed width and height, and set its class to sticky-top to make the div sticky on the top of the page.
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap 5 Position Sticky top</title>
<link href=
"https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity=
"sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
crossorigin="anonymous">
<script src=
"https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"
integrity=
"sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
crossorigin="anonymous"></script>
<style>
body {
height: 3000px;
}
.box {
width: 250px;
height: 100px;
border: 1px solid #312d2d;
margin: 0 auto;
}
</style>
</head>
<body>
<h3 class="text-center">
Bootstrap 5 Position Sticky top
</h3>
<div class="box sticky-top"></div>
</body>
</html>
Output:
Example 2: In this example, we will create an image element of fixed width and height, and set its class to sticky-top to make the image sticky on the top of the page.
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap 5 Position Sticky top</title>
<link href=
"https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity=
"sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
crossorigin="anonymous">
<script src=
"https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"
integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
crossorigin="anonymous"></script>
<style>
body {
height: 3000px;
}
</style>
</head>
<body>
<h3 class="text-center">
Bootstrap 5 Position Sticky top
</h3>
<img src=
"https://media.w3wiki.org/wp-content/cdn-uploads/20190710102234/download3.png"
class="sticky-top mx-auto d-block"
alt="GFG Logo">
</body>
</html>
Output:
Bootstrap 5 Position Sticky Top
Bootstrap 5 position-sticky class fixes an element at the top of the viewport when scrolling down. If not fully supported, alternatives like `position: fixed` or JavaScript solutions can mimic the sticky effect.
Position Sticky Top Class:
- sticky-top: This class is used to set the position of the element to the sticky top of the viewport when users scrolls down the page.
Syntax:
<div class="sticky-top">
Content
</div>