css-sticky-elements

May 9, 2019

Tutorials

CSS sticky elements tutorial

CSS position sticky was introduced in css 3 and it gives the element with this position a dynamic behavior, the element automatically switches between relative and fixed positions on scroll.

Sticky elements can be useful for navbars, sidebars, html documentations, ads, etc. position sticky is currently supported by almost all popular browsers.

HTML

In this simple example we have a parent div with relative position and four children with sticky position.

<div class='parent'>
  <div class='sticky one'>1</div>
  <div class='sticky two'>2</div>
  <div class='sticky three'>3</div>
  <div class='sticky four'>4</div>
</div>

CSS

In order to make sticky elements work as expected, their parent must be have relative position and all elements with sticky position should have one of top or bottom properties.

body{
  font-family:sans-serif;
  text-align: center;
  margin:0px;
}

.parent{
  position: relative;
  height: 3000px;
}

.sticky{
  position: sticky;
  width: 100%;
  height: 70px;
  top:0;
  padding-top: 30px;
  color: white;
  font-size:30px;
}

.sticky:not(:first-child){
  margin-top:500px;
}

.one{
  background: tomato;
}

.two{
  background: slateblue;
}

.three{
  background: darkorange;
}

.four{
  background: seagreen;
}

Final Result

See the Pen CSS only sticky navbars by Hosein Hamzenejad (@envoy47) on CodePen.0