Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using scroll-behavior: smooth for only one page with CSS

Tags:

css

When I enter the code

html {
    scroll-behavior: smooth;
}

I get the smooth effect that I want for anchor links. However, I only want this effect to apply to a single page, not my whole site. So I thought that perhaps this would work, using the class for the body tag of the single page that I want this effect on.

.landing-page {
    scroll-behavior: smooth;
}

However, once I do this the effect doesn't work, even though using the inspect tool shows that this attribute is applied to .landing-page. Why isn't it working, and what should I try next?

EDIT: Here is the HTML. I am trying to have it that I smooth scroll to #how-it-works and only that anchor.

<body class="landing-page welcome">
<div class="page first">
  <div class="container">
    <div class="heading">
      <a class ="anchor" id="how-it-works"></a>
      <span class="primary-text">
        You have before you the best system for deeply learning math.
      </span>
      <span class="secondary-text">
        Online, real tutors, at your own pace. Ask anything.
      </span>
    </div>
  </div>
</div>
</body>
like image 458
Wesley Avatar asked Apr 27 '26 23:04

Wesley


1 Answers

Ok one of the issues on your code is that the smooth scroll is not supported by the body tag, try adding a class or an id to your html tag, or just add it on that page inline coded, but it really depends on what restrictions you would have.

html.landing-page {
  overflow-y: scroll;
  scroll-behavior: smooth;
}

.container {
 width: 200px;
 marging: auto;
}
<html class="landing-page">
<body class="welcome">
<div class="page first">
  <div class="container">
    <div class="heading">
      <a class ="anchor" id="how-it-works"></a>
      <span class="primary-text">
        You have before you the best system for deeply learning math.
      </span>
      <span class="secondary-text">
        Online, real tutors, at your own pace. Ask anything.
        Online, real tutors, at your own pace. Ask anything.
        Online, real tutors, at your own pace. Ask anything.
        Online, real tutors, at your own pace. Ask anything.
        Online, real tutors, at your own pace. Ask anything.
        Online, real tutors, at your own pace. Ask anything.
        
      </span>
    </div>
  </div>
</div>
</body>
</html>

Another way would be having the code in a div instead of the HTML, but you would have to do some workarounds for it.

.landing-page {
  overflow-y: scroll;
  scroll-behavior: smooth;
  display: block;
  height: 100vh; // test with smaller heights
}
like image 89
Somelight Avatar answered Apr 30 '26 14:04

Somelight



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!