Parallax effect with pure CSS

Parallax effect with pure CSS

To create a simple parallax effect it is quite possible to do without using third-party plugins and libraries. Moreover, to implement a simple parallax effect, only CSS code using 3d perspective and pseudo-element.

HTML markup

You need a header tag header, title h1 and some text.

    

    Только CSS, никакого JavaScript

CSS styles

Property perspective gives the element a perspective, and transform-style sets the transformation style. The parallax effect is achieved by transforming blocks at different speeds, which creates a sense of depth. We will achieve the depth effect using 3d.


body {
    margin: 0; /* обнуление полей */
    padding: 0; /* обнуление отступов */
    perspective: 1px;/* задание перспективы трансформации */
    transform-style: preserve-3d; /* задание стиля трансформации */
    overflow-y: scroll; /* разрешить скролл по вертикали */
    overflow-x: hidden; /* спрятать все лишнее по горизонтали */
    font-family: 'Pacifico', cursive; /* семейство шрифтов */
    color: #fff; /* цвет текста */
}

header {
    box-sizing: border-box; /* ширина рамок и отступов не влияют на ширину элемента */
    min-height: 100vh; /* шапка занимает 100% первого экрана по высоте */
    text-align: center;/* выравнивание по центру */
    padding-top: 20%; /* поля со всех сторон */
    transform-style: inherit; /* значение наследуется от родителя body */
    width: 100vw; /* шапка занимает 100% ширины экрана */
    font-size: 34px; /* размер шрифта */
}

Pseudo element styles before are key to achieving the parallax effect, which lies in the values ​​of the property transform… The transformation will take place along the axis Z: The background image is shifted 1 pixel deep. The background picture moves slower than the title.


header::before {
    content: ''; /* условие отображения псевдоэлемента */
    display: block; /* позиционирование псевдоэлемента */
    position: absolute; /* позиционирование псевдоэлемента */
    left: 0; /* левая координата */
    right: 0; /* правая координата */
    bottom: 0; /* нижняя координата */
    top: 0;/* верхняя координата */
    z-index: -1; /* расположение на нижнем слое */
    transform-origin: center; /* направление трансформации из центра */
    min-height: 100vh;/* 100% по высоте */
    background-image: url('https://cdn.pixabay.com/photo/2020/12/22/12/38/cat-5852139_1280.jpg');
    background-repeat: no-repeat; /* запрет на размножение фона */
    background-size: cover; /* растянуть фон, сохраняя пропорции */
    transition: 1s; /* плавный переход */
    /* Параллакс */
    transform: translateZ(-1px) scale(2);
}

header h1 {
    margin-top: -100px;
    font-size: 40px;
}

Take a look at an example at CodePen

If you do not have enough knowledge for a better perception of this lesson, then watch my video course “Website layout from scratch 2.0”.

Previous article Next article

Copying of materials is allowed only with the indication of the author (Mikhail Rusakov) and an indexed direct link to the site (http://myrusakov.ru)!

Add to my friends VK: http://vk.com/myrusakov.
If you want to rate me and my work, then write it in my group: http://vk.com/rusakovmy.

If you do not want to miss new materials on the site,
then you can subscribe to updates: Subscribe to updates

If you still have any questions, or you have a desire to comment on this article, then you can leave your comment at the bottom of the page.

Recommend this article to your friends:

If you liked the site, then post a link to it (on your site, on the forum, in contact):

  1. Button:

    It looks like this: How to create your website

  2. Text link:

    It looks like this: How to create your website

  3. BB-code of the link for forums (for example, you can put it in the signature):

Related Posts

Property Management in Dubai: Effective Rental Strategies and Choosing a Management Company

“Property Management in Dubai: Effective Rental Strategies and Choosing a Management Company” In Dubai, one of the most dynamically developing regions in the world, the real estate…

In Poland, an 18-year-old Ukrainian ran away from the police and died in an accident, – media

The guy crashed into a roadside pole at high speed. In Poland, an 18-year-old Ukrainian ran away from the police and died in an accident / illustrative…

NATO saw no signs that the Russian Federation was planning an attack on one of the Alliance countries

Bauer recalled that according to Article 3 of the NATO treaty, every country must be able to defend itself. Rob Bauer commented on concerns that Russia is…

The Russian Federation has modernized the Kh-101 missile, doubling its warhead, analysts

The installation of an additional warhead in addition to the conventional high-explosive fragmentation one occurred due to a reduction in the size of the fuel tank. The…

Four people killed by storm in European holiday destinations

The deaths come amid warnings of high winds and rain thanks to Storm Nelson. Rescuers discovered bodies in two separate incidents / photo ua.depositphotos.com Four people, including…

Egg baba: a centuries-old recipe of 24 yolks for Catholic Easter

They like to put it in the Easter basket in Poland. However, many countries have their own variations of “bab”. The woman’s original recipe is associated with…

Leave a Reply

Your email address will not be published. Required fields are marked *