CSS sticky implementation returns to the top

Time:2022-1-8

You can often see such a “return to the top” function in some documents or articles. There are two interactions

  1. Only when you scroll a certain distance will it appear. Return to the top and hide again
  2. Click to return to the top

such as LuLu UI

CSS sticky implementation returns to the top

It’s both click and scroll. It seems that you have to use itJavaScriptIn fact, it’s not necessary. After some thinking, only a little CSS can achieve such interactive effects. Let’s have a look

1、 Viscous rolling

It’s needed hereA little imaginationYes. For example, it appears only after scrolling to a certain distance. Is it a little similarCSS stickyThe concept of? However, the general function of sticky is to scroll to a certain distance and then fix it to a certain position. MDN explains as follows

The element is located according to the normal document flow, and then relative to itsNearest scrolling ancestorandcontaining block(nearest block level ancestor), including table related elements, based ontop, right, bottom, andleftOffset the value of. The offset value does not affect the position of any other element.

Although there is a way out for the interaction we need, it can still be combined through certain “skills” to simply realize the layout first

<a class="back"></a>
<article>
... Many contents
</article>

Note here that you need to.backPut it in front, or you can’t trigger viscous positioning, and then.backPlus sticky positioning

.back{
  position: sticky;
  display: block;
  top: 0;
  border-radius: 50%;
  background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 320 512'%3E %3Cpath fill='%23ffffff' d='M177 159.7l136 136c9.4 9.4 9.4 24.6 0 33.9l-22.6 22.6c-9.4 9.4-24.6 9.4-33.9 0L160 255.9l-96.4 96.4c-9.4 9.4-24.6 9.4-33.9 0L7 329.7c-9.4-9.4-9.4-24.6 0-33.9l136-136c9.4-9.5 24.6-9.5 34-.1z'%3E%3C/path%3E %3C/svg%3E") center no-repeat dodgerblue;
  background-size: 50%;
  width: 50px;
  height: 50px;
}

Because of thetopThe given is 0, so the return button is pasted on the top during scrolling, as shown below

CSS sticky implementation returns to the top

At this time, if you puttopWhat happens if you change it to a negative value?

.back{
  /**/
  position: sticky;
  top: -30px;
}

As you can see, the button will go beyond the screen-30pxFixed in place as follows

CSS sticky implementation returns to the top

Then we put.backOffset the entire screen distance down, that is100vh

.back{
  /**/
  position: sticky;
  top: -30px;
  transform: translateY(100vh);
}

In this way, it is very close to the effect we need, but only a part appears in the end, as follows

CSS sticky implementation returns to the top

The principle is as follows:

CSS sticky implementation returns to the top

Finally, take what you just saidtopSet it smaller until.backCan appear completely, such as setting-60px

.back{
  /**/
  position: sticky;
  top: -60px;
  transform: translateY(100vh);
}

CSS sticky implementation returns to the top

This is basically done, but there are still some problems. Let’s move on

2、 Processing in the lower right corner

The above implementation actually has two layout problems to be optimized:

  1. The button itself occupies a certain space
  2. The button is generally located in the lower right corner

CSS sticky implementation returns to the top

Generally, in order to make an element occupy no space, you may think of setting absolute positioning. But here because of the settingposition: stickyTherefore, absolute positioning can no longer be set. In addition, we can also use floatingfloat, you can easily solve the above two layout problems

.back{
  /***/
  float: right
}

Setting the right float has two advantages: one is that it is separated from the document flow and does not affect the height; the other is to achieve the right float effect. The actual effects are as follows

CSS sticky implementation returns to the top

In fact, there is still a small problem here. When there are many words in the head, you can clearly see the right surround effect, as shown below

CSS sticky implementation returns to the top

How to deal with it? It’s simple, add a negativemarginThat’s it

.back{
  /***/
  float: right;
  margin-top:-50px;/* Self height*/
}

But there was a new problem, and the button at the bottom leaked out again

CSS sticky implementation returns to the top

becausetopHas beenstickyOccupied, now you can only change the position of the button bytransformYes, it can be used herecalcCalculate, andtopAlso reduce your height accordingly

.back{
  /***/
  float: right;
  margin-top:-50px;/* Self height*/
  top: -110px; /*60 + 50*/
  transform: translateY(calc(100vh + 50px));
}

CSS sticky implementation returns to the top

Perfect!

3、 Back to top

It’s easier to return to the top. Generally, you canhref='#'Can be achieved, of course, for smooth scrolling, you can addscroll-behavior: smooth

html, body { 
  scroll-behavior:smooth; 
}

The actual effect is as follows

CSS sticky implementation returns to the top

Finally, attach the complete code, very few

html,body{
  scroll-behavior: smooth;
}
.back{
  position: sticky;
  float: right;
  top: -110px;
  margin-top: -50px;
  border-radius: 50%;
  background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 320 512'%3E %3Cpath fill='%23ffffff' d='M177 159.7l136 136c9.4 9.4 9.4 24.6 0 33.9l-22.6 22.6c-9.4 9.4-24.6 9.4-33.9 0L160 255.9l-96.4 96.4c-9.4 9.4-24.6 9.4-33.9 0L7 329.7c-9.4-9.4-9.4-24.6 0-33.9l136-136c9.4-9.5 24.6-9.5 34-.1z'%3E%3C/path%3E %3C/svg%3E") center no-repeat dodgerblue;
  background-size: 50%;
  width: 50px;
  height: 50px;
  transform: translateY(calc(100vh + 50px));
}

HTML only needs to add a tag at the beginning

<body>
  <a class="back" href="#"></a><!-- Just add it here -- >
  <article>
  ... Many contents
  </article>
</body>

Online code accessibleback-top (codepen.io)

4、 Summary and description

The above realizes a small interaction of automatically displaying the return button with the help of CSS sticky. The amount of code itself is not complex. In fact, it is a little imagination. Associating more similar effects and trying more may bring different solutions. The following is a summary of the key implementation points:

  1. CSS sticky can achieve sticky scrolling effect, and negative values can be set
  2. Transformy (100vh) can offset 1 screen height without affecting the space occupation
  3. Floating can be separated from the document flow without affecting the height
  4. Negative margin can counteract the floating surround effect
  5. Scroll behavior: smooth enables smooth scrolling
  6. Compatibility depends on sticky, not ie

It is still a relatively practical small function. Although JS can also be implemented, why bother JS if it can be implemented with CSS? Compared with JS, CSS is simple and convenient to use, does not need to consider the loading problem, and has almost zero cost. Finally, if you think it’s good and helpful to you, you’re welcome to like, collect and forward ❤❤❤

Recommended Today

Proper memory alignment in go language

problem type Part1 struct { a bool b int32 c int8 d int64 e byte } Before we start, I want you to calculatePart1What is the total occupancy size? func main() { fmt.Printf(“bool size: %d\n”, unsafe.Sizeof(bool(true))) fmt.Printf(“int32 size: %d\n”, unsafe.Sizeof(int32(0))) fmt.Printf(“int8 size: %d\n”, unsafe.Sizeof(int8(0))) fmt.Printf(“int64 size: %d\n”, unsafe.Sizeof(int64(0))) fmt.Printf(“byte size: %d\n”, unsafe.Sizeof(byte(0))) fmt.Printf(“string size: %d\n”, […]