Как закрепить блок при прокрутке страницы
Блок со свойством position: sticky; при прокрутке страницы закрепляется относительно окна браузера опираясь на заданные значения top и/или left , при этом взаимодействует с другими элементами и закрепляется только тогда, когда родительский блок находится в отображаемом окне браузера и закрепленному элементу достаточно места в родительском блоке
Важно понять что для элемента с position: sticky; необходим родительский элемент, у которого будет свободное пространство для закрепленного элемента, если этого пространства нет, то блок со свойством position: sticky; будет вести себя как при position: static; установленном по-умолчанию для всех элементов
Еще раз для наглядности:
- Блоку <div > заданы свойства position: sticky; и top: 100px;
- Блок <div > находится в родительском блоке <div >
- Высота блока <div > меньше высоты родительского блока <div >
В итоге, при прокрутке страницы, как только блок <div > достигает расстояние 100px от верха окна браузера, закрепляется. Пока родительский блок <div > находится в пределах отображаемого окна браузера и блоку <div > достаточно места, он будет закреплен, как только места становится недостаточно, то блок открепляется от указанных 100px от верха окна браузера и прокручивается выше вместе с родительским блоком
Отличие от position: fixed;
При position: fixed; элемент никак не взаимодействует с другими элементами, он позиционируется относительно окна браузера отдельно от остальных элементов
Свойство position: fixed; полезно если элемент всегда должен находится в пределах окна браузера и не должен взаимодействовать с другими элементами, например, при верстке кнопки “Наверх” для возврата к началу страницы, которую обычно располагают справа внизу относительно окна браузера — она всегда видна и не затрагивает остальные элементы
Как закрепить шапку сайта
Блоку <div > добавляем свойство position: sticky; и top: 0; . Родительским элемент для блока <div > является <body> , поэтому при прокрутке страницы блок <div > закрепляется к самому верху окна браузера, пока body будет оставаться в пределах отображаемого окна браузера, а так как <body> основной родительский элемент для всей страницы, то блок <div > будет всегда закреплен к верху окна браузера
Если будем закрелять шапку сайта свойством position: fixed; , то шапка сайта не будет взаимодействовать с другими элементами и следующие за шапкой элементы будут перекрыты шапкой или шапка будет перекрыта следующими элементами в зависимости от z-index .
Свойство position: sticky; поддерживается во всех браузерах, кроме Internet Explorer. В Internet Explorer верстка не ломается, просто элементы остаются по умолчанию position: static; и будут прокручиваться не закрепляясь, поэтому можно использовать данный прием в проектах.
Как на самом деле работает position: sticky в CSS
У position: sticky уже очень неплохая браузерная поддержка, но большинство разработчиков так и не используют это свойство.
У этого есть две основные причины: во-первых, браузерам потребовалось много времени на реализацию адекватной поддержки этого свойства. И все просто успели забыть о нём.
Во-вторых, многие разработчики до конца не понимают логику, по которой это свойство работает. И тут появляюсь я!
Я полагаю, что вы хорошо знакомы с позиционированием в CSS, но давайте кратко повторим основные моменты:
Ещё три года назад существовало четыре типа позиционирования: static , relative , absolute и fixed .
Основное различие между static и relative , absolute и fixed в том, какое место они занимают в потоке документа (DOM). Элементы с позицией static и relative сохраняют своё естественное положение в потоке документа, в то время как absolute и fixed «вырываются» из потока документа и становятся плавающими.
Новое значение sticky похоже на все предыдущие значения сразу. Я проиллюстрирую это чуть позже.
Моё первое знакомство с «липким» позиционированием
Думаю, что большинство из вас игрались с «липким» позиционированием. Так было и у меня, пока в один момент я не осознал, что совсем не понимаю это свойство.
При первом знакомстве с position: sticky все быстро понимают, что элемент залипает, когда область просмотра достигает определённой позиции.
Проблема в том, что иногда это работает, а иногда нет. Когда всё работает, то элемент и правда залипает. Но когда не работает, то при прокрутке элемент перестаёт залипать. Как человеку, который живёт одним только CSS, мне было важно разобраться в сути проблемы. Именно поэтому я решил тщательно изучить «липкое» позиционирование.
«Липкая» разведка
Во время своих экспериментов я заметил, что если элемент с position: sticky является единственным ребёнком своего родителя-обёртки, то этот «липкий» элемент не залипает.
Когда я добавлял больше элементов внутрь родителя-обёртки всё начинало работать как ожидалось.
Почему так происходит?
Причина кроется в том, что элемент с position: sticky может перемещаться только в пределах контейнера, в котором находится. А поскольку в моём случае он был единственным ребёнком, у него не было элементов-братьев, поверх которых он мог перемещаться.
Как на самом деле работает position: sticky в CSS
«Липкое» позиционирование состоит из двух основных частей: «липкого» элемента и «липкого» контейнера.
«Липкий» элемент — это элемент, которому мы задали position: sticky . Элемент будет становиться плавающим, как только область видимости достигнет определённой позиции, например top: 0px .
«Липкий» контейнер — это HTML-элемент, который оборачивает «липкий» элемент. Это максимальная область, в которой может перемещаться наш элемент.
Когда вы задаёте элементу position: sticky , его родитель автоматически становится «липким» контейнером!
Очень важно это запомнить! Контейнер будет являться областью видимости для элемента. «Липкий» элемент не может выйти за пределы своего «липкого» контейнера.
В этом причина, почему в предыдущем примере «липкий» элемент не залипал: он был единственным дочерним элементом контейнера.
Понимание «липкого» поведения
Как я и говорил, position: sticky ведёт себя не так, как другие типы позиционирования. Но, с другой стороны, у них есть определённые сходства. Позвольте мне пояснить:
Относительное (или статичное) — «липкий» элемент похож на элемент со статическим или относительным позиционированием поскольку сохраняет свою естественную позицию в DOM (остаётся в потоке).
Фиксированное—когда элемент залипает, то ведёт себя как будто у него заданы стили position: fixed , остаётся на той же позиции в области видимости и вырывается из потока документа.
Абсолютное—в конце доступной для перемещений области элемент останавливается и остаётся поверх другого элемента. Точно также, как ведёт себя абсолютно спозиционированный элемент в контейнере с position: relative .
Залипает внизу?!
В большинстве случаев вы будете использовать position: sticky чтобы прикрепить элемент к верхнему краю страницы. Что-то вроде этого:
Именно для таких сценариев и был создан этот тип позиционирования. До его появления такой трюк приходилось проворачивать с помощью JavaScript.
Но вы с тем же успехом можете использовать это свойство для того, чтобы прилепить элемент к нижней границе. Это значит, что футеру можно задать «липкое» позиционирование и при скролле он всегда будет залипать у нижнего края. И когда мы дойдём до конца «липкого» контейнера наш элемент остановится на своей естественной позиции. Лучше использовать эту особенность для элементов, находящихся в самом конце контейнера.
В реальной жизни я использую такое поведение для сводных таблиц. И, я думаю, с помощью этого приёма можно реализовать «липкую» навигацию в футере.
Браузерная поддержка
- «Липкое» позиционирование поддерживается всеми основными современными браузерами. Исключение: старый-добрый IE.
- Для Safari потребуется префикс -webkit
В заключении
Вот и всё. Я надеюсь, что вам понравилась эта статья и мне удалось поделиться своим опытом. Я буду признателен, если вы поделитесь этим постом и поаплодируйте.
CSS Position Sticky Tutorial With Examples[Complete Guide]
171483 Views
16 Min Read
Seven to eight years back, CSS developers brought a fifth child into the positioning element world. The name of this element was “sticky” because all it does is get ‘stick’ to the viewport and just be in your sight (depending on the developer though). Although the sticky property of an element gives a name to a particular property in CSS, it does not bring anything ‘new” to the table. If I say, “let’s use a sticky div box,” you know what I am talking about, but before its release people would just define what they wanted to do like “Can I have a div box that would always be visible or available even if the people are scrolling?”
The entire point of bringing this up is to tell you that stickiness existed in web development long before it was introduced as a standard in CSS. This post will dive into the CSS position sticky, and we will find out how to get the CSS position fixed. Before we do that, let’s briefly see how people used the position sticky property before its official release.
TABLE OF CONTENT
Need For Position Sticky In CSS
As I mentioned, the position sticky in CSS was used even before it came out as a standard in CSS. So, why did they introduce it when everything was working fine?
Apart from CSS, the stickiness can be achieved through JavaScript also. In JavaScript, we make the use of scroll event handlers and calculate the offset of the page. With these values, we make calculations to stick the element as soon as the offset reaches a point. This used to work earlier, but for the last eight-nine years, scroll handlers became a total mess when better graphics were introduced in the systems.
The problem with scroll handlers is that unlike CSS, it relies on the CPU for doing its job. On the other hand, CSS uses hardware acceleration (a standard on all the browsers now for better cross browser compatibility), which means it relies on the GPU for doing its job. Due to this, we would often see the UI of the website, breaking down quickly when the sticky element is coded in JavaScript. A better solution to this is bringing the stickiness to the GPU. The only way to do that is by introducing it as a standard in CSS. Looking back, it actually makes a lot of sense. So, the “sticky” property was added to the positions which already had four values. To understand how to get “CSS position fixed,” we should know the behavior of other CSS values.
CSS Position And Its Values
The position attribute in CSS is used to define the position of the element used in the browser window. With CSS position fixed, you can manipulate how the element behaves using different values of this property. Before the value “sticky” came into the picture, CSS: Position had four different values:
Static: The element with a static value remains with the natural flow of the document. Specifying positions through the top, left, right, etc., will not affect this element. This is also the default behavior of an element in HTML.
Relative: The relative value is the same as the static value but now the left, right, top, bottom values will affect the position of the element. So, the position of the element will become relative to its default position and hence the word relative. Although, it is important to remember that moving this element will not affect other elements and they will still remain in their actual position and actual space. If z-index is not set properly, your two elements might overlap like this:
Absolute: The absolute value of CSS: Position takes the element out of the normal flow of the page and searches for the closest parent (ancestor) which is available with the position set to either relative or absolute. When such an ancestor is found, this element is moved relative to this ancestor by using left, right, top, bottom specified values. If there is no such ancestor that has this property, the default ancestor will become an element and this element will be placed relative to i.e. the web page itself.
Fixed: An element with the fixed property is fixed with respect to the container block which most of the time is the browser’s window also called the viewport. The benefit of having a fixed position sticky element is that it does not move even though you scroll the window. The best example is the navigation bar, which is fixed by the developers at a single place most of the time. But, it should be noted that the container block is not always the viewport of the browser. The container element can change if any of the ancestors of the fixed element has a transformative, perspective, or filter property set to something else other than none. In such cases, this ancestor becomes the container block, and the fixed element’s behavior changes accordingly. When the block position is identified, the final position depends on the top, left, right, bottom properties only. This is a great way to get your CSS position fixed.
The floating behaviour of fixed and absolute often causes problems in designing the user interface unknowingly or when the developer does not have prior knowledge. Since these elements are set relative to some other element in the HTML, they sometimes overlap other elements partially or fully and hide those elements. Actually, it is really impossible to note down the number of situations where you can go wrong while designing a web page. Every time, there is something different happening in the code. In the case of CSS position sticky, the developer is often sure about the static and relative elements since they are always on the natural flow of the document and do not depend on other elements but fixed and absolute should be used very carefully.
What is CSS Position Sticky?
The fifth value of the CSS: Position that came after all of the values discussed above is the sticky value. A position sticky element toggles between the relative value and the fixed value on the viewport. The state on which the CSS sticky element is currently present depends on the scroll position of the browser window.
The position of the CSS sticky element depends upon the given offset or a threshold top, bottom, left, and right value that the developer provides. If the element has not yet reached the threshold, it retains in the relative position. Once the threshold is reached, you’ve got the CSS position fixed and the elements get “stuck” to the same block. This is not a one-time operation though. The CSS position sticky element toggles between these two positions depending on the scroll of the page. So, a CSS position sticky element that is currently “fixed” will move back to the “relative” when it will meet the opposite end of its container block.
The following GIF shows how a CSS position sticky element looks:
The above GIF contains a CSS position sticky element which is the heading of the document: Do You Know All About Sticky Element? You can see that while I scroll the document, it still sticks to the viewport.
How To Create A Position Sticky Element Using CSS?
You need to create position sticky elements to achieve what they call ‘CSS position fixed’. As I have shown you above, a CSS position sticky is always in the website visitor’s viewport. Creating a position sticky element in CSS as I did above is very easy. But you will have to keep two things in mind:
- Declaring the position value as sticky for the element.
- Defining a relative value (also called the threshold value).
How To Design A CSS Sticky Header?
A sticky header can be used to stick the heading of a paragraph to the browser window. So, if the paragraph changes and so does it’s heading, a new heading sticks to the browser until the user scrolls the complete paragraph. The following code has been used to create a sticky header:
In the code above, I have made the element sticky with the id = ”sticky-div”. In the styling part, to make this element sticky, I have given top:0 because I don’t want any gap between the sticky element and viewport boundary.
Position: sticky specifies that I need to have this element as sticky. With these two parameters, you can make your element or CSS position sticky in no time. The above-coded web page looks as follows:
How To Design A Sticky Footer In CSS?
Footer on a website is a great way to catch the eye of the users on something that you want them to see every time they load the website and even without scrolling. In the below example, consider an article where I want the author’s name to be visible all the time. You can use the same code that we have used above with a slight adjustment to make the heading as a footer.
Прилипающий блок CSS
Элемент с position: sticky; фиксируется в рамках ближайшего родителя, когда расстояние до границы ближайшего прокручиваемого родителя достигает указанного в свойствах top , right , bottom , left значения. На то, в каком месте элемент прикрепится и где отцепиться, также влияют свойства padding , margin и transform . Размещение элемента над другими элементами правится с помощью свойства z-index .
После того, как свойство position примет значение sticky , размер элемента не изменится, а соседние элементы не сдвинутся на освободившееся пространство.