Home > Blockchain >  HTML CSS smooth scrolling is not working with ID's and classes
HTML CSS smooth scrolling is not working with ID's and classes

Time:03-20

.box {
  width: 200px;
  height: 200px;
  text-align: center;
  padding: 50px;
}

.hrefbox {
  scroll-behavior: smooth;
}

#box1 {
  background: red;
}

#box2 {
  background: blue;
}

#box3 {
  background: green;
}

#box4 {
  background: peru;
}

#box5 {
  background: purple;
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>This is my Website</title>
</head>

<body>
  <ul>
    <li><a href="#box1" ; >Box 1</a></li>
    <li><a href="#box2" ; >Box 2</a></li>
    <li><a href="#box3" ; >Box 3</a></li>
    <li><a href="#box4" ; >Box 4</a></li>
    <li><a href="#box5" ; >Box 5</a></li>
  </ul>
  <div id="box1" ; >BOX 1</div>
  <div id="box2" ; >BOX 2</div>
  <div id="box3" ; >BOX 3</div>
  <div id="box4" ; >BOX 4</div>
  <div id="box5" ; >BOX 5</div>
</body>

</html>

I tried to make smooth scrolling with a class (.hrefbox) but it didn't work. I tried with "body" tag too, didn't work either. I have no idea is this normal or did I something wrong, I'm new at this.

CodePudding user response:

Set the scroll behavior on html.

html {
  scroll-behavior: smooth;
}

See it working here:

.box {
  width: 200px;
  height: 200px;
  text-align: center;
  padding: 50px;
}

html {
  scroll-behavior: smooth;
}

#box1 {
  background: red;
}

#box2 {
  background: blue;
}

#box3 {
  background: green;
}

#box4 {
  background: peru;
}

#box5 {
  background: purple;
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>This is my Website</title>
</head>

<body>
  <ul>
    <li><a href="#box1" ; >Box 1</a></li>
    <li><a href="#box2" ; >Box 2</a></li>
    <li><a href="#box3" ; >Box 3</a></li>
    <li><a href="#box4" ; >Box 4</a></li>
    <li><a href="#box5" ; >Box 5</a></li>
  </ul>
  <div id="box1" ; >BOX 1</div>
  <div id="box2" ; >BOX 2</div>
  <div id="box3" ; >BOX 3</div>
  <div id="box4" ; >BOX 4</div>
  <div id="box5" ; >BOX 5</div>
</body>

</html>

  • Related