Position sticky css не работает chrome

position: sticky НЕ работает

Видео: position: sticky НЕ работает

Наверняка Вы уже знаете о таком значении свойства position в CSS, как sticky . Но как у начинающих, так и у продвинутых верстальщиков, оно вызывает массу вопросов. Одним из основных является то, как именно работает это и при каких условиях.

Для справки: position: sticky – это одно из новых значений свойства position , которое позволяет элементам прилипать к необходимой части экрана, во время прокрутки страницы. И не надо никакого JS. Данное значение свойства позволяет использовать удобные и простые навигационные и информационные элементы, не прибегая к использованию JS кода.

Как работает это значение, Вы наверняка знаете, но я все же напомню.

Есть родительский элемент (к примеру). В нем есть заголовок

, а также с длинным текстом. И таких элементов на странице несколько (может быть и один, несколько чисто для примера).

Чтобы пользователь мог видеть заголовок

при прокрутке странице, и не забывал о чем идет речь, при изучении длинного текста (возможно с видео/изображениями), логично представить, что расположив элемент

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

Важно задать РОДИТЕЛЬСКОМУ элементу position: relative , дочернему элементу: position: sticky; top: 0 >> элемент прилипнет к верху страницы, если задать bottom: 0 , то, соответственно, к низу.

САМОЕ ГЛАВНОЕ!

Для html , body НЕ ДОЛЖНО использоваться свойство overflow: hidden или overflow-x: hidden . Иначе, position: sticky НЕ сработает вообще .

ТАКЖЕ position: sticky не работает, если использовать новое свойство CSS — backdrop-filter . То есть, родительский контейнер НЕ должен иметь это свойство. Или же тот контейнер, на котором возникает полоса прокрутки.

Источник

Почему position: sticky в некоторых случаях не работает?

Почему position: sticky; не срабатывает? Заметил, что в некоторых случаях работает, а в некоторых нет, но не могу понять почему.

1 ответ 1

Элемент позиционируется в соответствии с нормальным потоком документа, а затем смещается относительно его ближайшего прокручивающего предка и содержит containing block (ближайший предка уровня блока), включая элементы, связанные с таблицей, на основе значений top , right , bottom , и left . Смещение не влияет на положение любых других элементов.

Это значение всегда создает новый stacking context. Обратите внимание, что липкий элемент «прилипает» к его ближайшему предшественнику, имеющему «механизм прокрутки» (созданный при overflow от hidden , scroll , auto , или overlay ), даже если тот не является ближайшим фактически прокручивающим предком. Это эффективно препятствует любому «липкому» поведению (см. Github issue on W3C CSSWG).

Читайте также:  Как отремонтировать светофильтр сварочной маски хамелеон

Всё ещё ищете ответ? Посмотрите другие вопросы с метками css или задайте свой вопрос.

Похожие

Подписаться на ленту

Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.

дизайн сайта / логотип © 2021 Stack Exchange Inc; материалы пользователей предоставляются на условиях лицензии cc by-sa. rev 2021.10.15.40479

Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.

Источник

Проблемы с position: sticky CSS и способ их решить

Дата публикации: 2019-02-26

От автора: в этой статье я хочу рассмотреть недостатки position: sticky; — в частности, как мы можем придумать креативную технику при работе с переполнениями, что вызывает разочарование при работе с нативным решением.

Липкие элементы или фиксированные панели часто используются в программах — особенно в приложениях на основе строк / столбцов, таких как Microsoft Excel. CSS position: sticky также широко используется в мобильных (нативных) приложениях и в веб-дизайне. Такие элементы помогают пользователям сохранять чувство перспективы при сортировке длинных списков или отслеживании деталей своих заказов при совершении покупок в Интернете.

Старый способ

Указать элементу, чтобы он вел себя липко и статично в окне браузера, было довольно сложно. До того, как (современные) браузеры представили нативное решение, нам приходилось прибегать к имитации поведения с помощью привязки (например, для заголовков, боковых панелей и т. д.) через javascript и position: fixed;. Javascript прослушивает события прокрутки и положение элемента в документе, и как только добавляется математика, вы вводите класс, скажем, «sticky», который назначает элементу position: fixed;, что приводит к тому, что элемент прилипание в соответствии с вашими инструкциями.

Довольно сложная техника для чего-то (что должно быть) достаточно простого. Этот метод имеет несколько (отчасти) очевидных ошибок:

элемент не расположен в потоке документа, что вызывает скачок, когда он становится в статическую позицию, и

Практический курс по верстке адаптивного сайта с нуля!

Изучите курс и узнайте, как верстать современные сайты на HTML5 и CSS3

потенциальное снижение производительности в результате непрерывных перерисовок и обратных вызовов из-за события прокрутки (вы могли бы справиться с проблемами производительности, используя такие методы, как дросселирование, отскок или даже Intersection Observer.

Способ sticky

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

Вы можете сделать это с помощью четырех строк кода:

Читайте также:  Hp 1522 не работает дисплей

Источник

Why doesn’t position: sticky work in Chrome?

How do you get position: sticky working?

I tried the following in Chrome 26.0.1410.43 m and it’s not working:

According to this, it should work:

It seemed to be supported in Chrome 23.0.1247.0, but now it doesn’t work in 26.0.1410.43 m.

7 Answers 7

For a short time, Chrome enabled this feature behind a flag, —enable-experimental-webkit-features , in their about:flags section. However, it was shortly removed due to inefficiencies in how the browser was repainting.

As of Chrome 56, this feature is enabled without a flag once again.

As of Chrome 52.0.2743.116, this feature is enabled by the flag —enable-experimental-webkit-features once more.

To answer the updated question about why it was removed: Google (Chromium) removed support for position: sticky due to the unfinished nature of the spec, and they will focus on other scrolling features in the mean-time:

«We would eventually like to implement position: sticky, but the current implementation isn’t designed in a way that integrates well with the existing scrolling and compositing system. For example, position: sticky relies upon updateLayerPositionsAfterDocumentScroll to function correctly, but that function has no other purpose and can otherwise be removed. Similarly, position: sticky doesn’t work at all with composited overflow scrolling, which is now the default mechanism for driving scrolling in the engine.

Once we’ve got our scrolling and compositing house in order, we should return to position: sticky and implement the feature in a way that integrates well with the rest of the engine. For now, however, this CL removes our current implementation so we can focus on improving our implementation of the scrolling features we’ve already shipped.»

Emphasis mine. You can read more about it here.

Источник

position:sticky is not working

I have this HTML code:

.header has a height of 150px. .navbar has a height of 20px. When the user scrolls, I want .navbar to stick at the top. So I went to the CSS and set position:sticky and top:0. But this didn’t work. I initially thought that firefox is not supporting position:sticky, but that’s not the case because I was able to see a working demo of it. I googled about it but found nothing helpful. Anyone knows why this is not working?

8 Answers 8

For anyone else that comes across this, position sticky was not working for me due to the body element having overflow-x: hidden; set.

It works fine if you move the navbar outside the header. See below. For the reason, according to MDN:

The element is positioned according to the normal flow of the document, and then offset relative to its flow root and containing block based on the values of top, right, bottom, and left.

For the containing block:

The containing block is the ancestor to which the element is relatively positioned

So, when I do not misunderstand, the navbar is positioned at offset 0 within the header as soon as it is scrolled outside the viewport (which, clearly, means, you can’t see it anymore).

Читайте также:  Что сделать если не работает 6300

The 2 most common culprits why position: sticky; might not work are:

  1. You haven’t defined top: 0; , bottom: 0; , left: 0 or something similar
  2. One of the parents of your sticky element has overflow (x or y) set to hidden , scroll or auto .

For me it was the first one.

To expand from the answers above and some information to make it work with flexbox parent and overflow other than visible (the examples below assume you use vertical — sticky with either top or bottom set to a certain value and position set to sticky):

The most frequent case is you have an ancestor element (not just immediate parent) with overflow property set to something other than visible and as a result there is no space is left to stick around. To quickly find out if this is the case, you can run this script in the browser console (please make sure you change the .your-sticky-element class to your element’s selector):

SOLUTION:

a) If you found there is overflow set, and you can remove it, this should solve it

b) If you have to keep your overflow setting, you have to make the parent element’s height higher than the sticky element’s height. If the parent element has no height or the sticky element fills up all the height, it means there is simply no place to stick within when the page is scrolled. It doesn’t need to an explicit height (vertical), but you can inspect to see if your sticky element has extra space left after itself.

Parent is not higher than the sticky element to leave extra space. This particular case can be caused by different circumstances but the solution to this is the same above, please see 1.b

If your sticky element’s parent is a flexbox (align-items has default value of normal) and if the sticky element itself doesn’t have a proper align-self set, there will be no space left for the sticky element to hold when scrolling (for example, if it is align-self: stretch or auto [default value]). This is because the child element is stretched to fill up the height of the parent.

SOLUTION:

In this case, align-self: flex-start set for the sticky element can fix the problem because in the element will stand at the start, leaving extra space after itself.

Guide: There are much more complex circumstances both in the case of flexboxes and without it, but the general rule of thumb is your sticky element needs space within the parent to be sticky when scrolled.

Источник

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