Home > Net >  Moving a CSS Element Vertically Without JS
Moving a CSS Element Vertically Without JS

Time:06-06

Is there anyway I can make an HTML div move down while scrolling instead of moving up without using javascript? I know you can use window.onscroll = function() { } and have that move the position of an object while scrolling, but is there anyway I can move an object down with just CSS and HTML?

CodePudding user response:

I think you want to retain your div on the viewport while scrolling down.

There are 2 ways for it.

  1. Make the element position fixed and apply positioning to that element.
  2. Make parent element position relative and make your div position sticky and apply positioning.

Positioning means adding any one of the top, right, bottom, and left properties.

.parent {
  height: 1200px;
  width: auto;
  position: relative;
}

.floating {
  position: sticky;
  top: 10px;
  width: 100%;
  height: 60px;
  background: black;
  color: white;
}
<div >
  <p>Hi this is parent</p>
  <div >
    This is floating element
  </div>
</div>

  • Related