vulkan vulkan - 3 years ago 208
CSS Question

Using ScrollTop in FlexBox does not work

nav, main, footer, there are 3 tags. I applied them to FlexBox :

body {
color: #ddd;
font-family: Gotham;
background: url(../assets/body-background.png);
display: flex;
min-height: 100%;
flex-direction: column;
}
main {
flex: 1;
}


everything looks so good. but things are getting worse after that

I have the following code in my script file (using jQuery):

$('.scroll-top').click(function () {
$('body').animate({
scrollTop: 0
}, 1000);
})


but the page scrolling animation is not working

jsfiddle



$('a').click(function(){
$('body').animate({
scrollTop: 0
}, 1000);
})

nav{
padding: 10px;
background: grey;
}
main{
height:800px;
background: lightgrey;
}
footer{
padding: 10px;
background: grey;
}
body{
display: flex;
min-height: 100vh;
flex-direction: column;
}
main{
flex: 1;
}
a{
position: fixed;
right: 40px;
bottom: 40px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<nav>nav content</nav>
<main>main content</main>
<a href="javascript:;">scroll top</a>
<footer>footer content</footer>




Answer Source

Its working fine in Chrome, but not working in Firefox. For the scroll to work in Firefox, you must use scrollTop on html:

$('body,html').animate({
  scrollTop: 0
}, 1000);

Also the main won't take the 800px you have assigned to it in Firefox. Change flex: 1 to flex: 1 1 800px for same behaviour cross-browser.

See demo below:

$('a').click(function() {
  $('body,html').animate({
    scrollTop: 0
  }, 1000);
})
nav {
  padding: 10px;
  background: grey;
}

main {
  height: 800px;
  background: lightgrey;
}

footer {
  padding: 10px;
  background: grey;
}

body {
  display: flex;
  min-height: 100vh;
  flex-direction: column;
}

main {
  flex: 1 1 800px; /* NEW */
}

a {
  position: fixed;
  right: 40px;
  bottom: 40px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<nav>nav content</nav>
<main>main content</main>
<a href="javascript:;">scroll top</a>
<footer>footer content</footer>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download