Table of Contents
Method 1: Use position: fixed
Method 2: Use position: sticky
Summarize
Home Web Front-end HTML Tutorial CSS implements the effect of moving elements vertically with the scroll bar: no JavaScript required

CSS implements the effect of moving elements vertically with the scroll bar: no JavaScript required

Aug 28, 2025 pm 06:03 PM

CSS implements the effect of moving elements vertically with the scroll bar: no JavaScript required

This article will explain how to use pure CSS to achieve the effect of elements moving vertically with the scroll bar without writing any JavaScript code. As mentioned in the summary, we will explore two main methods: using position: fixed and position: sticky. Both methods can enable elements to remain in a specific position in the viewport when the page is scrolling, thereby improving the user experience.

Method 1: Use position: fixed

The position: fixed attribute fixes the element at a position relative to the viewport. This means that the element will always remain in the same position on the screen no matter how the user scrolls the page.

Sample code:

 


<title>Fixed Position Example</title>
<style>
body {
  height: 2000px; /* In order to generate scrollbar*/
}

.fixed-element {
  position: fixed;
  top: 10px; /* 10 pixels from the top*/
  left: 10px; /* 10 pixels from the left side*/
  background-color: lightblue;
  padding: 10px;
  border: 1px solid black;
}
</style>



<div class="fixed-element">
  This is a fixed positioning element.
</div>

<p>Scroll the page and you will find that this element is always kept in the upper left corner of the screen. </p>
<p> (Add enough content is added here to generate scrollbars)</p>

Code explanation:

  • The .fixed-element class uses position: fixed; to set the element to fixed positioning.
  • top: 10px; and left: 10px; define the distance from the top and left of the viewport.
  • The top, left, right and bottom attributes can be adjusted as needed to change the position of the element.

Notes:

  • position: fixed removes elements from normal document streams, thus may affect the layout of other elements.
  • Make sure that fixedly positioned elements do not obstruct important content.

Method 2: Use position: sticky

The position: sticky property behaves similarly to the combination of position: relative and position: fixed. Before scrolling to a specific threshold, an element appears as position: relative; when scrolling to a threshold, it appears as position: fixed.

Sample code:

 


<title>Sticky Position Example</title>
<style>
body {
  height: 2000px; /* In order to generate scrollbar*/
}

.parent {
  position: relative; /* The parent element needs to be set to relative */
  height: 500px; /* Set the height of the parent element to observe sticky effect*/
  border: 1px solid gray;
  margin-bottom: 20px;
}

.sticky-element {
  position: sticky;
  top: 0; /* fixed when scrolling to top*/
  background-color: lightgreen;
  padding: 10px;
  border: 1px solid black;
}
</style>



<div class="parent">
  <div class="sticky-element">
    This is an element that is sticky.
  </div>
  <p>Scroll the page and you will find that this element is pinned there when scrolling to the top. </p>
</div>

<p> (Add enough content is added here to generate scrollbars)</p>

Code explanation:

  • The .sticky-element class uses position: sticky; Sets the element to sticky positioning.
  • top: 0; defines the fixed position of the element when scrolling to the top of the parent element.
  • The parent element needs to set position: relative;, otherwise position: sticky; may not work properly.

Notes:

  • position: sticky You need to specify the top, right, bottom, or left attributes to determine when to switch to fixed positioning.
  • position: sticky's behavior is affected by the parent element to ensure that the parent element is layout correctly.
  • If the height of the parent element is smaller than that of the viscous positioning, the effect of viscous positioning may not be seen.

Summarize

This article introduces two methods to use CSS to achieve the effect of elements moving vertically with scroll bars. position: fixed is suitable for elements that need to be always fixed in the viewport, and position: sticky is suitable for elements that need to be fixed when scrolling to a specific position. Choose the appropriate method according to actual needs, which can easily achieve various scrolling effects and improve user experience. In actual applications, it is necessary to pay attention to the impact of element positioning on page layout and make appropriate adjustments.

The above is the detailed content of CSS implements the effect of moving elements vertically with the scroll bar: no JavaScript required. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

CSS tips: precisely hide specific text content without affecting parent elements CSS tips: precisely hide specific text content without affecting parent elements Sep 16, 2025 pm 10:54 PM

This tutorial details how to use CSS to accurately hide specific text content in HTML pages to avoid the problem of the entire parent element being hidden due to improper selectors. By adding exclusive CSS classes to the wrapping elements of the target text and using the display: none; attribute, developers can achieve refined control of page elements, ensuring that only the required parts are hidden, thereby optimizing page layout and user experience.

How to create a hyperlink to an email address in html? How to create a hyperlink to an email address in html? Sep 16, 2025 am 02:24 AM

Usemailto:inhreftocreateemaillinks.Startwithforbasiclinks,add?subject=and&body=forpre-filledcontent,andincludemultipleaddressesorcc=,bcc=foradvancedoptions.

How to make text wrap around an image in html? How to make text wrap around an image in html? Sep 21, 2025 am 04:02 AM

UseCSSfloatpropertytowraptextaroundanimage:floatleftfortextontheright,floatrightfortextontheleft,addmarginforspacing,andclearfloatstopreventlayoutissues.

How to set the lang attribute in HTML How to set the lang attribute in HTML Sep 21, 2025 am 02:34 AM

Setthelangattributeinthehtmltagtospecifypagelanguage,e.g.,forEnglish;2.UseISOcodeslike"es"forSpanishor"fr"forFrench;3.Includeregionalvariantswithcountrycodeslike"en-US"or"zh-CN";4.Applylangtospecificelementswhe

Capture mousedown events with parent element containing cross-domain iframes: Principles and limitations Capture mousedown events with parent element containing cross-domain iframes: Principles and limitations Sep 20, 2025 pm 11:00 PM

This article explores the challenge of capturing mousedown events on parent divs containing cross-domain iframes. The core problem is that browser security policies (same-origin policy) prevent direct DOM event listening on cross-domain iframe content. This type of event capture cannot be achieved unless the iframe source domain name is controlled and CORS is configured. The article will explain these security mechanisms in detail and their limitations on event interactions and provide possible alternatives.

JavaScript external function call difficulty analysis: script location and naming specification JavaScript external function call difficulty analysis: script location and naming specification Sep 20, 2025 pm 10:09 PM

This article explores two common problems when calling external JavaScript functions in HTML: improper script loading time causes DOM elements to be unready, and function naming may conflict with browser built-in events or keywords. The article provides detailed solutions, including tweaking script reference locations and following good function naming specifications to ensure JavaScript code is executed correctly.

How to add a tooltip on hover in html? How to add a tooltip on hover in html? Sep 18, 2025 am 01:16 AM

UsethetitleattributeforsimpletooltipsorCSSforcustom-styledones.1.Addtitle="text"toanyelementfordefaulttooltips.2.Forstyledtooltips,wraptheelementinacontainer,use.tooltipand.tooltiptextclasseswithCSSpositioning,pseudo-elements,andvisibilityc

Implement vertical stacking of elements in Bootstrap Flexbox layout: from side to layer Implement vertical stacking of elements in Bootstrap Flexbox layout: from side to layer Sep 21, 2025 pm 10:42 PM

When using Bootstrap for web page layout, developers often encounter the problem of elements being displayed side by side rather than stacked vertically by default, especially when the parent container applies Flexbox layout. This article will explore this common layout challenge in depth and provide a solution: by adjusting the flex-direction attribute of the Flex container to column, using Bootstrap's flex-column tool class to achieve the correct vertical arrangement of H1 tags and content blocks such as forms, ensuring that the page structure meets expectations.

See all articles