Scroll to top button creates extra white space at the bottom of the page
P粉226642568
2023-08-13 19:52:48
<p>I followed some tutorials to create a CSS based floating scroll to top button. However, I noticed that there is extra white space below the last HTML element (e.g. the last line). The height of the extra white space matches my button height (50px). </p>
<p> I also tried adding an extra div tag to enclose the arrowUp div tag, and the gap was reduced, but there is still some small but noticeable white space. </p>
<p>I was wondering if there was a way to avoid the extra white space? </p>
<pre class="brush:css;toolbar:false;">#arrowUp {
position: sticky;
width: 50px;
bottom: 120px;
background: #699462;
border-radius: 10px;
aspect-ratio: 1;
margin-left: auto;
margin-right: 20px;
// margin-bottom: 150px;
}
#arrowUp a {
content: "";
position: absolute;
inset: 25%;
transform: translateY(20%) rotate(-45deg);
border-top: 5px solid #fff;
border-right: 5px solid #fff;
}</pre>
<pre class="brush:html;toolbar:false;"><div>
<p> First line. </p>
<br /><br /><br /><br />
<br /><br /><br /><br />
<br /><br /><br /><br />
<br /><br /><br /><br />
<br /><br /><br /><br />
<br /><br /><br /><br />
<br /><br /><br /><br />
<br /><br /><br /><br />
<br /><br /><br /><br />
<br /><br /><br /><br />
<br /><br /><br /><br />
<br /><br /><br /><br />
<br /><br /><br /><br />
<br /><br /><br /><br />
<br /><br /><br /><br />
<br /><br /><br /><br />
<br /><br /><br /><br />
<br /><br /><br /><br />
<br /><br /><br /><br />
<p> Last line. </p>
</div>
<div id="arrowUp">
<a href="#"></a>
</div></pre>
<p><br /></p>
I think in your case it's better to use
position: fixed;
instead ofsticky
. Note that you need to setright: 0;
to position the "button" on the right edge of the screen. Alternatively, you can setright: 20px;
and remove the margin attribute.Quick explanation
The "extra whitespace" exists because when
sticky
is used, the element is positioned within the normal flow of the document. It's like usingposition: relative;
and settingtop: -20px
- the element moves up 20px, but the original space is preserved because it "stays" in the document flow. Usingposition: fixed;
will remove the element from the document flow.I recommend reading about document flow and positioning in CSS: