Signup/Sign In
PUBLISHED ON: AUGUST 6, 2021

How to create a sticky element with CSS?

The sticky element sticks at the particular position of the browser. The position of the element does not change even when the contents on the webpage are too short or too long.

In this tutorial, we will be learning about the CSS properties to create a sticky element with CSS.

Create Sticky Element

The position:sticky property is used to position the element relative to the viewport. A sticky element is positioned: relative until the given offset and then sticks to the given position like position:fixed .

In addition to that use top, bottom, left, or right property to position the element.

Example: Create a sticky element with CSS

In this example, we have added a sticky element with position: sticky property and top:0. The element is position relative till it reaches the top and then it sticks at the top of the page and the rest element gets scrolled.

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>HTML </title>
    <style>
      .container {
        position: sticky;
		height: 50px;
        top:0;
        width: 100%;
        background-color: #CCCCCC;
        color: black;
        text-align: center;
		font-size: 25px;
      }
      h2,
      p {
        text-align: center;
      }
    </style>
  </head>
  <body>
    <h2> Sticky element</h2>
    <p> Here we have created a sticky footer </p>
	<h2> Scroll here </h2>
	<h2> Scroll here </h2>
	<h2> Scroll here </h2>
	<h2> Scroll here </h2>
	<h2> Scroll here </h2>
	<h2> Scroll here </h2>
	<h2> Scroll here </h2>
    <div class="container">
      <p>The sticky element</p>
    </div>
	<h2> Scroll here </h2>
	<h2> Scroll here </h2>
	<h2> Scroll here </h2>
	<h2> Scroll here </h2>
	<h2> Scroll here </h2>
	<h2> Scroll here </h2>
	<h2> Scroll here </h2>
	<h2> Scroll here </h2>
	<h2> Scroll here </h2>
	<h2> Scroll here </h2>
  </body>
</html>

Output

Here is the output of the above code.

sticky element

Example: Creating a sticky menu

In this example, we have created a sticky menu that sticks at the top of the viewport.

Conclusion

In this tutorial, we have learned to create sticky elements with CSS. Use position: sticky to create sticky elements. We can add a sticky menu or sticky footer using this property.



About the author: