The scroll bar on the left-hand side of the div element

Как создать скроллинг на своем сайте с помощью CSS?

Вы хотите создать эффекты параллакса и скроллинга на странице, но не знаете, с чего начать? Не нужно сразу обращаться к Javascript: есть более простые варианты. В этой статье мы расскажем, как все сделать при помощи СSS-кода. Также объясним, с какими браузерами эффекты работать не станут.

Если нужен плавный скроллинг

Чтобы создать простую прокрутку из одной части страницы в другую, нужно использовать CSS-свойство scroll-behavior. Вот его основные значения:

Так выглядит CSS-код на примере со вторым значением и условным селектором p:

Далее мы покажем на примере, как сделать плавный переход от одной части сайта к другой при помощи значения smooth. В этом случае пользователь увидит переход при нажатии на гиперссылку, ведущую к другой части с текстом.

Пример с HTML-кодом

Шаг 1. Создадим два блока с ссылками друг на друга:





Плавная прокрутка




Блок 1


Перейди по гиперссылке, чтобы увидеть плавный скроллинг.


Нажми сюда, чтобы перейти к Блоку 2.



Блок 2


Нажми сюда, чтобы перейти к Блоку 1.



Шаг 2. Добавим плавный скроллинг с помощью кода CSS внутри тега . Код состоит из cвойства scroll-behavior и значения smooth. Еще выберем цвета и высоту для разных частей с текстом: розовый и желтый.

 



Благодаря значению smooth удалось добиться плавного скроллинга на веб-странице.

Совместимость с браузерами

Свойство scroll-behavior работает почти со всеми популярными браузерами: Google Chrome, Firefox, Safari и Opera. Исключение — Internet Explorer и старые версии браузеров. Например, на Safari версии 15.2–15.3 свойство работать не станет.

Если нужен параллакс

Parallax — это эффект, при котором элементы заднего плана движутся быстрее или медленнее, чем объекты на переднем плане. Например, пользователь прокручивает страницу и видит, что фоновое изображение движется с одной скоростью, а текст — с другой.

Пример с HTML-кодом

В этом случае мы сделаем так, чтобы фоновая картинка вообще не двигалась во время скроллинга.

Шаг 1. Напишем код, в котором будет большой текстовый блок фиолетового цвета:

 




Прокрутите страницу дальше






Этот текст нужен просто для того, чтобы продемонстрировать эффект. Вам стоит прокрутить страницу вверх и вниз — текстовый блок будет двигаться, а изображение останется на месте.





Шаг 2. Рассмотрим код CSS. В нем будет ссылка на изображение, которая станет фоновым благодаря значению fixed в свойстве background-attachment.

В итоге получился параллакс на странице.

Читайте также:  Изменение цвета текста

Примечание. Чтобы убрать этот эффект, достаточно вместо background-attachment: fixed указать в коде background-attachment: scroll. Изображение будет двигаться вместе с текстом:

Совместимость с браузерами

Свойство background-attachment работает с Google Chrome, Firefox, Opera, Internet Explorer и другими браузерами. Исключение — Safari, Android Browser и мобильная версия Opera.

Дополнительные примеры

Чтобы лучше разобраться с CSS-свойствами, рассмотрим другие эффекты для прокрутки на сайте .

Пример 1

По шагам рассмотрим, как добиться эффекта многоуровневого скроллинга . В этом случае несколько объектов на сайте будут двигаться с разной скоростью при прокрутке.

Шаг 1. Напишем две строки следущим образом:

Шаг 2. Добавим CSS-код внутри тега . Сначала укажем параметры и выберем фон на бесплатном фотостоке для блока 2:

 



Шаг 3. Там же укажем параметры заголовков:

 



Шаг 4 . Определим параметры других элементов:

 



В итоге на сайте движутся три объекта. Перечислим их от самого медленного до самого быстрого:

Так выглядит многоуровневый скроллинг.

Пример 2

Рассмотрим, как зафиксировать какой-либо элемент на сайте во время прокрутки. Например, на сайте cloud.timeweb.com есть такой закрепленный блок:

Шаг 1 . Напишем код с двумя текстовыми блоками таким образом:

 

Зафиксированный элемент






Элемент


Шаг 2. Напишем следующий CSS-код внутри тега :



При помощи свойства значения fixed удалось сделать так, чтобы элемент двигался вместе с прокруткой.

Пример 3

В этом случае разберемся, как сделать горизонтальный скроллинг.

Шаг 1. Создадим четыре строки текста таким образом:

Шаг 2 . Добавим CSS-код внутри тега . В коде обозначим размеры текстовых блоков и их цвета.

 

Так выглядит горизонтальная прокрутка страницы, которая условно разделена на несколько частей с текстом.

Заключение

Создание эффекта скроллинга — это несложный процесс. Только при помощи свойств CSS можно сделать так, чтобы пользователь видел необычные переходы между блоками сайта при прокрутке.

В некоторых случаях нужны длинные коды: например, для многоуровневого варианта, при котором каждый блок на странице движется с уникальной скоростью. Но это в любом случае лучше, чем создавать подобные переходы на JavaScript.

Источник

Styling Based on Scroll Position

Rik Schennink documents a system for being able to write CSS selectors that style a page when it has scrolled to a certain point. If you’re like me, you’re already on the lookout for document.addEventListener(‘scroll’ . and being terrified about performance. Rik gets to that right away by both debouncing the function as well as marking the event as passive . The end result is a data-scroll attribute on the element that can be used in the CSS. Meaning if you’re scrolled to 640px down the page, you have and could write a selector like:

html:not([data-scroll='0']) < padding-top: 3em; >html:not([data-scroll='0']) header

See the Pen
Writing Dumb JS 🧟‍♂️ and Smart CSS 👩‍🔬 by Rik Schennink (@rikschennink)
on CodePen. Unfortunately, we don’t have greater than ( > ) less than ( < ) selectors in CSS for things like numbered attributes, so the CSS styling potential is fairly limited here. You might ultimately need to update the JavaScript function such that it applies other classes or data attributes based on your math. But you’ll already be set up for good performance here. “Apply styles when the user has scrolled away from the top” is a legit use case. It makes me think of a once function (like we have in jQuery) where any scroll event would only be triggered once and then not again. They scrolled! So, by definition, they aren’t at the top anymore! But that doesn’t deal with when they scroll back to the top. I find it generally more useful to use IntersectionObserver for styling things based on scroll position. With it, you can do things like, “has this element been scrolled into view or beyond,” which is generically useful and can be used for scrolled-away-from-top stuff too. Here’s an example that adds or removes a class if a user has scrolled past a hidden pixel positioned at 500px down the page. See the Pen
Fixed Header with IntersectionObserver by Chris Coyier (@chriscoyier)
on CodePen. That’s performant as well, avoiding any scroll event handlers at all. And speaking of IntersectionObserver , check out “Trust is Good, Observation is Better—Intersection Observer v2”.

Читайте также:  Simple admin php code

Psst! Create a DigitalOcean account and get $200 in free credit for cloud-based hosting and services.

Источник

How to change the position of the scrollbar using CSS?

A scrollbar refers to the element that allows a user to scroll through the content of a web page. It usually appears as a horizontal or vertical bar on the side or bottom of the page. The scrollbar is also known as the «scrollbar thumb,» which is the part of the scrollbar that moves when the user scrolls up and down.

In this article, we will discuss how to change the position of a scrollbar using CSS. We will cover the following topics −

  • Creating a new class for the element
  • Targeting the scrollbar and the thumb
  • Using the «position» property to change the position of the scrollbar

Creating a new class for the element

First, we will need to create a new class in CSS for the element that we want to change the scrollbar position for. For example, if we want to change the position of the scrollbar for a div with the class «scrollablediv,» we will create the following class in CSS —

.scrollable-div  CSS Code……. > ::-webkit-scrollbar  width: 5px; background-color: #F5F5F5; >

This class will target the scrollbar for the «scrollable-div» element and set the width to 5 pixels and the background color to a light gray.

Targeting the thumb of the scrollbar

In this step, we target the thumb of the scrollbar. The thumb is the part of the scrollbar that moves when the user scrolls. We will do this by adding the following code to CSS class −

::-webkit-scrollbar-thumb  background-color: #000000; >

This will change the color of the thumb to black.

Using the «position» property to change the position of the scrollbar

In this final step, we will change the position of the scrollbar by using the «position» property. For example, if we want to position the scrollbar on the left side of the «scrollable-div» element, we will use the following code −

.scrollable-div::-webkit-scrollbar  position: absolute; left: 0; >

This will position the scrollbar on the left side of the «scrollable-div» element.

Example

This example puts the scroll bar on the Left-hand side of the div element.

   body < text-align:center; >.scrollable-div < height: 150px; width: 250px; overflow-y: auto; background-color:pink; margin:auto; padding:5px; transform: rotate(180deg); >.scrollable-div-inside < transform: rotate(-180deg); >.scrollable-div::-webkit-scrollbar < width: 5px; /* Set the width of the scrollbar */ background-color: #F5F5F5; /* Set the background color of the scrollbar */ position: absolute; right: 0; /* Position the scrollbar on the right of the element*/ >.scrollable-div::-webkit-scrollbar-thumb < background-color: #000000; /* Set the color of the thumb */ >::-webkit-scrollbar-track 

The scroll bar on the Left side of the div element

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.

Example

This example puts the scroll bar on the right-hand side of the div element.

   body < text-align:center; >.scrollable-div < height: 150px; width: 250px; overflow-x: auto; background-color:pink; margin:auto; padding:5px; >.scrollable-div::-webkit-scrollbar < width: 5px; /* Set the width of the scrollbar */ background-color: #F5F5F5; /* Set the background color of the scrollbar */ position: absolute; left: 0; /* Position the scrollbar on the left of the element */ >.scrollable-div::-webkit-scrollbar-thumb < background-color: #000000; /* Set the color of the thumb */ >::-webkit-scrollbar-track 

The scroll bar on the right side of the div element

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.

Conclusion

Changing the position of a scrollbar using CSS is a simple process that can be done by creating a new class for the element, targeting the scrollbar and the thumb, and then using the «position» property to change the position of the scrollbar. With a little bit of CSS knowledge and some experimentation, we can create a unique and custom look for the website.

Источник

Оцените статью