Last Updated:

Fixed background effect when scrolling

Sometimes you don't need to know js to come up with creative and pleasing to the eye effects. In today's tutorial, we'll talk about an interesting CSS technique, namely background attachment. You can set the background for mounting in the viewport. We'll use this in scrolling and displaying the background in the area we need. The effect is to change the background image in two ways, the first is the general background in which the information will be displayed, and the second is a fixed phone with different elements.

Many different free templates you can find on the website of our partners, there are also premium templates with round-the-clock technical support and help in setting up:

We have prepared in advance a selection of different images, with the same size and graphics for a common element that will be fixed in a single position.

Step 1. HTMLs

The HTML structure is quite simple: each section contains a .content element with a title and a paragraph. The .img-1, .img-2, etc. classes are used to set various background images in CSS:



And .cd-vertical-nav is an element of the navigation arrow (visible only on large devices). Data types have been used for identification in jQuery partitions.

Fixed background effect when scrolling on CSS

Step 2. CSS

A couple of important things to keep in mind: iOS devices don't like the background-attachment property: fixed; Therefore, on devices with a small screen, the fixed background effect will not be visible. Also, on smaller devices, we don't use CSS for background images, but we don't enter large photos of phones, as well as ::after for pseudo-elements and a .cd-content element.



Secondly, since we use backgrounds with images, we cannot fully control how this background will be displayed on different devices (mobile). It's hard to accept if you're obsessed with website design excellence, but we haven't been able to find a solution for it. This is all the code we need for a fixed background effect:



Step 3. JS


We used jQuery to implement the main slider for navigating through various sections (previous/next arrows and keyboard navigation). In the scroll window, we update (visibility arrows by checkNavigation()). NextSection() and prevSection() will use functions to move on to the next/previous section.